C# 7.2 New Features

Version 7.2 is the second release introducing several new features. This release requires Visual Studio 2017 15.5 or later. The new features are...

Readonly references

In addition to ref and out keywords, C# 7.2 add the in keyword. It is used to specify that the method is receiving a value type by reference but it is not allowed to modify it. This is enforced by the compiler. This can increase performance as strings or structs can be passed by ref.

void Test()
    var msg = "Error message";
    Log(in msg);

private void Log(in string msg)
    Console.WriteLine($"{DateTime.Now}: {msg}");

Another addition is the ref readonly modifier, it can be used to return a read only reference to an object. This can be used to return a static instance and be sure that it won't be modified.

private static object staticObject = new object();
public static ref readonly object StaticObject => ref staticObject;

Two other additions are the readonly and ref structs. The readonly structs as the name suggests are read-only, this is enforced by the compiler. They should always be passed by read-only reference. The ref structs give you the ability to create value types that must be allocated on the stack.

Non-trailing named arguments

In C# 7.2 you can use named arguments before positional arguments as long as they are in the correct position.

Leading underscores

In C# 7 you could use _ as separator in numeric literals. In this release you can also use the _ as the first character in a binary or hex literals this allows you to separate the hex/binary prefix.

int hexVal = 0X_ABC_DEF;
int binaryVal = 0b_1010_0110;

Private protected

In this version of C# we see the addition of the private protected modifier. It allows access by the containing class or derived classes that are declared in the same assembly. In contrast, the protected internal allows access to derived classes or classes in the same assembly.


Popular posts from this blog

Electron JS, Visual Studio Code, and SQL Operations Studio

Unity vs. Unreal Engine

Free & Paid Resources for Getting Started in IT