Microsoft is plowing ahead with the development of C# 9.0, an upgrade to the company’s type-safe, object-oriented language that will include new capabilities such as records and value-based equality.
C# 9.0 is due to be part of the .NET 5 development platform, set to arrive in November. C# 8.0 arrived last September. The new features in C# 9.0, detailed at Build this week by C# lead designer Mads Torgersen, include the following:
- Records, for declaring a whole object to be immutable and have it behave like a value. Records are intended to be seen more like data and less like objects.
withexpressions, which use object initializer syntax to show what is different in a new object compared to an old one.
- Improved pattern matching.
- Value-based equality. All objects inherit a virtual
Equals(object)method from the
objectclass. This serves as a basis for the
Object.Equals(object, object)static method when both parameters are non-null. Structs override this to have “value-based equality,” allowing comparisons of each field of the struct by calling
Equalson them in a recursive manner. Records also do this. Thus, in accordance with “value-ness,” two record objects can be equal without being the same object.
- Relational patterns, which are patterns corresponding to relational operators
<=, and so on.
- Logical patterns, which combine patterns with logical operators
not, spelled out as words to avoid confusion with operators used in expressions
- Simple type patterns.
- Init-only properties, introducing an i
nitassessor that is a variant of the
setassessor, for calling during object initialization. These properties address a limitation of object initializers, in which properties must be mutable for these initializers to work.
- Improved target typing, which is a term describing when an expression gets its type from the context where it is being used. For example,
nulland lambda expressions are always targeted. With C# 9.0, some expressions that were not previously target-typed now can be guided by their context.
newexpressions, in which the type can be left out if there is a clear type that the expression is being assigned to.
- Covariant returns, to express that a method override in a derived class has a more specific return type than the declaration in the base type.
- Positional records, providing an approach to records where contents are given via constructor arguments and can be extracted with positional deconstruction.
- Top-level programs, to address the issue of too much boilerplate code.