Deep Dive Into C# 9

 
 
The official planned next C# release is C# 9. You can find in this link the Language Version Planning for C#·
 
 
 
As shown above, in the list, there are 27 proposals/features are planned for C# 9, but that does not mean that all of those proposals will be released in C# 9.
 
Which proposal will be released, and in which version? The .Net development team can only answer all these questions. They have the final decision, and they can change their minds all the time, both on proposed features and syntax/semantics of these features.
 
The most important features planned for C# 9, namely record types, unfortunately Discriminated Unions is moved to C# 10 plan, more pattern matching enhancements, and additional target-typing of existing constructs such as ternary and null-coalescing expressions.
 
In this article, I will describe Record and Discriminated Unions and the other proposals I will describe them briefly.
 

!!!!! Important !!!!!

 
Particularly for both Records and Discriminated Unions, they are not in the final stage. They both still need a lot of work to move from the current strawman proposal syntax to what their final designs will be.
 

Records

 
I have been waiting for a long time for this feature. Records are a lightweight type. They are nominally typed, and they might have (methods, properties, operators, etc.), and allow you to compare structural equality! Also, the record properties are read-only by default. Records can be Value Type or Reference Type. Records are useful to represents a complex data with many properties, like a database record or some model entity, DTO's, etc.
  • Read-only properties => Immutable Type
  • Equality implementations => Structural equality
  • Pattern-matching support = is pattern, switch pattern etc.
The Proposal in GitHub here.
 
The most up-to-date proposal for records is here.
 
In my previous articles, I have described the Positional Records and this article I will talk about the Nominal Records. If you are not familiar with those terms, don’t worry: I will simplify them as best I can. Basically, C# allows us to write the code in a positional or nominal style. Let us first take a look at the Object initializers.
 
Object initializers allows to create an object in a very flexible and readable format:
 
Microsoft Example:
  1. // The following code:    
  2. public class Person    
  3. {  
  4.     public string FirstName { getset; }    
  5.     public string LastName { getset; }    
  6. }       
  7. // Can be created as follows    
  8. new Person    
  9. {    
  10.     FirstName = "Scott",    
  11.     LastName = "Hunter"    
  12. }    
  13. p.FirstName = “Alugili” // Works no Error!
"The one big limitation today is that the properties have to be mutable for object initializers to work" Init-only properties fix that!
  1. public class Person    
  2. {    
  3.     public string FirstName { get; init; }    
  4.     public string LastName { get; init; }    
  5. }    
  6. Person p = new Person    
  7. {    
  8.     FirstName = "Scott",    
  9.     LastName = "Hunter"    
  10. }    
  11. p.FirstName = “Alugili” // Error !  
Note: init-only properties are also useful to make individual properties immutable.
 

Positional Records and the Nominal Records

 
C# allows you to write the code with a positional or nominal code style. Object initializer belongs to the nominal category. Until C# 8, the nominal category is restricted because it required writable properties. The introduced “init” accessor removes this limitation in C# 9.
 

Nominal Records

 
Nominal data is defined as data that is used for naming or labeling variables.
 
Example:
  1. data class User {string Name, int Age};    
  2. var user = new User {Name = "Bassam", Age= 43};    
  3. var copyUser = user with {Name = "Thomas"};    

Positional Records

 
The variables in ordinal data are listed in an ordered manner.
  1. data class User(string Name, int Age);    
  2. var user = new User("Bassam", 43);    
  3. // Change the data    
  4. var copyUser = user with {Name = "Thomas"};    
  5. // Deconstruction    
  6. (string name, int age) = user;          
  7. // Pattern matching (Type Pattern)    
  8. if (user is ("Bassam", _))    
  9.     Console.Write($“My Name is {user.Name}”);    

Structural Equality & Referential Equality

 
Usually, records are compared by structure and not by reference. In C# 9 we can make both approaches.
 

Referential Equality (Identity)

 
Means that the pointers for two objects are the same when they have the same memory location, which leads us to the fact that pointers reference to the same object.
 
Identity: determines whether two objects share the same memory address.
 

Structural Equality

 
Means that two objects have equivalent content.
 
Equality: determines if two objects contain the same state.
 
Example:
  1. data class User (string name, int age);    
  2. public static void Main(){    
  3. User user = new User( "Bassam", 43);    
  4. User user2 = new User( "Bassam", 43);      
  5. if (Equals(user, user2))    
  6. {    
  7.     Console.WriteLine("Structural Equality !");    
  8. }    
  9. if (ReferenceEquals(user, user2))    
  10. {    
  11.     Console.WriteLine("!!!! The code will not execute!!!!");    
  12. }
Output: 
Structural Equality!
 
Besides, Records support inheritance, which makes Records in C# unique and varies from the most functional programming languages and F#.
 
Inheritance in Records Example
  1. abstract data class User {string name, int age};    
  2. data class SuperUser:User {bool IsAdmin};    
  3. var user = new SuperUser(FirstName = "Bassam", Age= 43, IsAdmin true);    
Inheritance - Records mutation and “with” expression
  1. // The runtime- type is preserved after the coping, consider the below example:    
  2. abstract data class User {string name, int age};    
  3. data class SuperUser:User {bool IsAdmin};      
  4. var user = new SuperUser(Name = "Bassam", Age= 43,IsAdmin true);    
  5. var copyUser = user with {Name = "Thomas"};    
  6. Console.WriteLine(copyUser.GetType().Name); // Output: SuperUser 
Nominal Records in Depth
 
The Nominal Records can be defined as follows:
  1. data class Point3D    
  2. {    
  3.     int X,  
  4.     int Y,  
  5.     int Z,  
  6. } 
Equivalent to:
 
The proposed solution is a new modifier, init, that can be applied to properties and fields,
  1. class Point3D    
  2. {    
  3.    int X { get; init;}    
  4.    int Y { get; init;}    
  5.    int Z { get; init;}   
  6.    ...    
  7.    ...    
  8. }   
Creating Record:
  1. void DoSomething()    
  2. {    
  3.   var point3D = new Point3D()  
  4.   {    
  5.     X = 1,    
  6.     Y = 1,    
  7.     Z =1    
  8.   };    
  9. }    
Record from the old proposal (Positional)
 
Example, the following record with a primary constructor
  1. data class Point3D(int X, int Y, int Z);  
Would be equivalent to:
  1. public class Demo    
  2. {    
  3.   public void CreatePoint()    
  4.   {    
  5.     var p = new Point3D(1.0, 1.0, 1.0);  
  6.   }    
  7. }  
Would be equivalent to:
  1. data class Point3D    
  2. {    
  3.   public int X { get; }    
  4.   public int Y { get; }    
  5.   public int Z { get; }    
  6.   public Point(int x, int y, int z)    
  7.   {    
  8.     X = x;    
  9.     Y = y;    
  10.     Z = z;    
  11.   }   
  12.   public void Deconstruct(out int X, out int Y, out int Z)  
  13.   {    
  14.     X = this.X;    
  15.     Y = this.Y;    
  16.     Z = this.Z;    
  17.   }    
  18. }    
The final generation of the above would be:
  1. class Point3D    
  2. {    
  3.   public initonly int X { get; }    
  4.   public initonly int Y { get; }    
  5.   public initonly int Y { get; }    
  6.   public Point3D(int x, int y, int z)    
  7.   {    
  8.     X = x;    
  9.     Y = y;    
  10.     Y = z;    
  11.   }    
  12.     
  13.   protected Point3D(Point3D other)    
  14.   : this(other.X, other.Y, other.Z)    
  15.   { }    
  16.     
  17.   [WithConstructor]    
  18.   public virtual Point With() => new Point(this);    
  19.     
  20.   public void Deconstruct(out int X, out int Y, out int Z)  
  21.     
  22.   {    
  23.   X = this.X;    
  24.   Y = this.Y;    
  25.   Z = this.Z;    
  26.   }    
  27.   // Generated equality    
  28. }   

Using Records and the With-expression

 
Records proposal is introduced with the new proposed feature "with-expression". In programming, an immutable object is an object whose state cannot be modified after it is created. If you want to change the object you have to copied it. The “with” help you to solve the problem, and you can use them together as the following.
  1. public class Demo    
  2. {    
  3.   public void DoIt()    
  4.   {    
  5.     var point3D = new Point3D() { X = 1, Y = 1, Z =1  };  
  6.     Console.WriteLine(point3D);    
  7.   }    
  8. }    
  9. var newPoint3D = point3D with {X = 42};  
The created new point (newPoint3D) just like the existing one (point3D), but with the value of X changed to 42.
 
This proposal is working very well with pattern matching.
 

Records in F#

 
Copy from F# MSDN example, type Point3D = {X: float; Y: float; Z: float}
  1. let evaluatePoint (point: Point3D) =    
  2.   match point with    
  3.         | { X = 0.0; Y = 0.0; Z = 0.0 } -  
  4. > printfn "Point is at the origin."    
  5.         | { X = xVal; Y = 0.0; Z = 0.0 } -  
  6. > printfn "Point is on the x-axis.  Value is %f." xVal  
  7.         | { X = 0.0; Y = yVal; Z = 0.0 } -  
  8. > printfn "Point is on the y-axis. Value is %f." yVal   
  9.         | { X = 0.0; Y = 0.0; Z = zVal } -  
  10. > printfn "Point is on the z-axis. Value is %f." zVal   
  11.         | { X = xVal; Y = yVal; Z = zVal } -  
  12. > printfn "Point is at (%f, %f, %f)." xVal yVal zVal    
  13.     
  14. evaluatePoint { X = 0.0; Y = 0.0; Z = 0.0 }    
  15. evaluatePoint { X = 100.0; Y = 0.0; Z = 0.0 }    
  16. evaluatePoint { X = 10.0; Y = 0.0; Z = -1.0 }   
The output of this code is as follows.
Point is at the origin.
Point is on the x-axis. Value is 100.000000.
Point is at (10.000000, 0.000000, -1.000000).
 
Record types are implemented by the compiler, which means you have to meet all of those criteria and can't get them wrong.
 
So not only do they save a lot of boilerplate, they eliminate an entire class of potential bugs.
 
Moreover, this feature existed over a decade in F#, and other languages like (Scala, Kotlin) have a similar concept too.
 
Examples for other languages that support both constructors and records.
 
F#
  1. type Greeter(name: string) = member this.SayHi() = printfn "Hi, %s" name  
Scala
  1. class Greeter(name: String)    
  2. {    
  3.   def SayHi() = println("Hi, " + name)  
  4. }  

Equality

 
Records are compared by structure and by reference
 
Example
  1. void DoSomething()      
  2. {      
  3.     var point3D1 = new Point3D()       
  4.     {      
  5.         X = 1,      
  6.         Y = 1,      
  7.         Z =1      
  8.     };      
  9.       
  10.     var point3D2= new Point3D()       
  11.     {      
  12.         X = 1,      
  13.         Y = 1,      
  14.         Z =1      
  15.     };      
  16.       
  17.     var compareRecords = point3D1 == point3D2; // true, operator overload or with Equal method     
  18. } 

Discriminated Unions (C# 10)

 
The term Discriminated Unions (disjoint union) is borrowed from mathematics. A simple example to understand the term.
 
Below the Venn diagram is shown(disjoint union) by two non-overlapping closed regions and said inclusions are shown by showing one closed curve lying entirely within another.
 
Two sets A and B are said to be disjoint, if they have no element in common.
 
Thus, A = {1, 2, 3} and B = {5, 7, 9} are disjoint sets; but the sets C = {3, 5, 7} and D = {7, 9, 11} are not disjoint; for, 7 is the common element of A and B.
 
Two sets A and B are said to be disjoint, if A ∩ B = ϕ. If A ∩ B ≠ ϕ, then A and B are said to be intersecting or overlapping sets.
 
 
Example 2
 
 
Discriminated union (disjoint union) is also widely used in the programming languages (especially in FP), which used to sum the existing data types.
 

Discriminated unions in C# 10

 
It offers a way to define types that may hold any number of different data types. Their functionality is similar to F# discriminated union.
 
It used for values that can be enumerated. For example, Do you like C#Corner? Answer Yes or No? It can't be anything else other than those two specific values(Yes or No).
You can imagine it like enums in C#.
 
The official proposal here.
 
Discriminated unions are useful for heterogeneous data; data that can have individual cases, with valid and error cases; data that vary in type from one instance to another. Besides, it offers an alternative for small object hierarchies.
 
F# discriminated union example.
  1. type Person = {firstname:string; lastname:string}  // define a     
  2. record type       
  3. type ByteOrBool = Y of byte | B of bool      
  4.       
  5. type MixedType =       
  6.     | P of Person        // use the record type defined above      
  7.     | U of ByteOrBool    // use the union type defined above      
  8.       
  9. let unionRecord = MixedType.P({firstname="Bassam"; lastname= "Alugili"});      
  10. let unionType1 =  MixedType.U( B true);   // Boolean type      
  11. let unionType2 =  MixedType.U( Y 86uy);   // Byte type 
C# 9 Discriminated Unions example.
 
Using C# records, this could potentially be expressed in C#, using a form of union definition syntax, as,
  1. // Define a record type      
  2. public class Person      
  3. {      
  4.   public initonly string Firstname { get; }      
  5.   public initonly string Lastname { get; }      
  6. };      
  7.       
  8. enum class ByteOrBool { byte Y; bool B;} // Just for demo the syntax is not fix now. 
We need a time that we need is a type that represents all possible integers PLUS all possible Booleans.
 
 
 
In other words, ByteOrBool is the sum type. In our case, the new type is the “sum” of the byte type plus the boolean type. And as in F#, a sum type is called a “discriminated union” type.
  1. enum class MixedType  
  2. {    
  3.   Person P;    
  4.   ByteOrBool U;    
  5. }  
Constructing a union instance,
  1. // Note: the “new” might be not needed!    
  2. var person = new Person()    
  3. {    
  4.   Firstname = ”Bassam”;    
  5.   Lastname = “Alugili”;    
  6. };    
  7.     
  8. var unionRecord = new MixedType.P(person); // Record C# 9    
  9. var unionType1 = new MixedType.U( B true); // Boolean type    
  10. var unionType2 = new MixedType.U( Y 86uy); // Byte type  

Usage of discriminated unions

 
With Pattern matching
 
Using the "subtype" names directly and the upcoming match expression. These below examples and are just for demo to make a better understanding for the proposal.
Exception handling like in Java,
  1. try    
  2. {    
  3.   …    
  4.   …    
  5. }    
  6. catch (CommunicationException | SystemException ex)    
  7. {    
  8.     // Handle the CommunicationException and SystemException here    
  9. }    
As type constraint
  1. public class GenericClass<T> where T : T1 | T2 | T3  
Generic class can be one of those types T1 or T2 or T3
 
Typed heterogeneous collections
  1. var crazyCollectionFP = new List<int|double|string>{1, 2.3, "bassam"};
Examples from the proposal,
 
Resultant type of combination of variables/values/expressions of different types through? :, ?? or switch expression combinators.
  1. var result = x switch { true => "Successful"false => 0 };  
The type of result here will be- string|int
 
If multiple overloads of some method have same implementations, Union type can do the job,
  1. void logInput(int input) => Console.WriteLine($"The input is {input}");  
  2. void logInput(long input) => Console.WriteLine($"The input is {input}");    
  3. void logInput(float input) => Console.WriteLine($"The input is {input}");    
Can be changed to
  1. void logInput(int|long|float input) => Console.WriteLine($"The input is {input}");  
Maybe as return types,
  1. public int|Exception Method() // returning exception instead of throwing    
  2.     
  3. public class None {}    
  4.     
  5. public typealias Option<T> = T | None; // Option type    
  6.     
  7. public typealias Result<T> = T | Exception; // Result type  
More Examples here.
 

Enhancing the Common Type Specification

 
The proposal here.
 

Target typed null coalescing ('??') expression

 
It is about allowing an implicit conversion from the null coalescing expression.
 
Example
  1. void M(List<int> list, uint? u)    
  2. {    
  3.   IEnumerable<int> x = list ?? (IEnumerable<int>)new[] { 1, 2 }; // C# 8    
  4.   var l = u ?? -1u; // C# 8    
  5. }    
  6.     
  7. void M(List<int> list, uint? u)    
  8. {    
  9.   IEnumerable<int> x = list ?? new[] { 1, 2 }; // C# 9    
  10.     
  11.   var l = u ?? -1; // C# 9    
  12. }  

Target-typed implicit array creation expression

 
Introducing the “new()” expression.
 
The official proposal Examples,
  1. IEnumerable<KeyValuePair<stringstring>> Headers = new[]  
  2. {    
  3.   new KeyValuePair<stringstring>("Foo", foo),    
  4.   new KeyValuePair<stringstring>("Bar", bar),    
  5. }  
Can be simplified to
  1. IEnumerable<KeyValuePair<stringstring>> Headers = new KeyValuePair<stringstring>[]    
  2. {    
  3.   new("Foo", foo),    
  4.   new("Bar", bar),    
  5. }    
But you still need to repeat the type following the field/property initializer. The closest you can get is something like:
  1. IEnumerable<KeyValuePair<stringstring>> Headers = new[]  
  2. {    
  3.   new KeyValuePair<stringstring>("Foo", foo),    
  4.   new("Bar", bar),    
  5. }  
For the sake of completeness, I'd suggest to also make new[] a target-typed expression.
  1. IEnumerable<KeyValuePair<stringstring>> Headers = new[]  
  2. {    
  3.   new("Foo", foo),    
  4.   new("Bar", bar),    
  5. }  

Target-typed new-expressions

 
“var” infers the left side, and this feature allows us to infer the right side.
 
Example
  1. Point p = new (x, y);    
  2. ConcurrentDictionary> x = new();    
  3. Mads example: Point[] ps = { new (1, 4), new (3,-2), new (9, 5) }; // all Points    

Caller Expression Attribute (Not C# 9)

 
Allows the caller to ‘stringify’ the expressions passed in at a call site. The constructor of the attribute will take a string argument specifying the name of the argument to stringify.
 
Example
  1. public static class Verify {      
  2.     public static void InRange(int argument, int low, int high,  
  3.       
  4.         [CallerArgumentExpression("argument")] string argumentExpression = null,      
  5.         [CallerArgumentExpression("low")] string lowExpression = null,      
  6.         [CallerArgumentExpression("high")] string highExpression = null) {      
  7.         if (argument < low) {      
  8.             throw new ArgumentOutOfRangeException(paramName: argumentExpression, message: $ " {argumentExpression} ({argument}) cannot be less than {lowExpression} ({low}).");      
  9.         }      
  10.         if (argument > high) {      
  11.             throw new ArgumentOutOfRangeException(paramName: argumentExpression, message: $ "{argumentExpression} ({argument}) cannot be greater than {highExpression} ({high}).");      
  12.         }      
  13.     }      
  14.     public static void NotNull < T > (T argument,      
  15.         [CallerArgumentExpression("argument")] string argumentExpression = null)      
  16.     where T: class {      
  17.         if (argument == nullthrow new ArgumentNullException(paramName: argumentExpression);      
  18.     }      
  19. }      
  20.     
  21. // CallerArgumentExpression: convert the expressions to a string!        
  22. Verify.NotNull(array); // paramName: "array"        
  23.     
  24. // paramName: "index"        
  25. // Error message by wrong Index:       "index (-1) cannot be less than 0 (0).", or      
  26.     
  27. // "index (6) cannot be greater than array.Length - 1 (5)."        
  28. Verify.InRange(index, 0, array.Length - 1);   

Default in deconstruction

 
Allows the following syntax (int i, string s) = default; and (i, s) = default;.
 
Example
  1. (int x, string y) = (defaultdefault); // C# 7  
  2. (int x, string y) = default// C# 9  

Relax ordering of ref and partial modifiers

 
Allows the partial keyword before ref in the class definition.
 
Example
  1. public ref partial struct {} // C# 7    
  2. public partial ref struct {} // C# 9  

Parameter null-checking

 
Allow simplifying the standard null validation on parameters by using a small annotation on parameters. This feature belongs to code enhancing.
 
Last meeting notes here.
 
Example
  1. // Before C# 1..7.x    
  2. void DoSomething(string txt)    
  3. {    
  4.     if (txt is null)    
  5.     {    
  6.        throw new ArgumentNullException(nameof(txt));  
  7.      }    
  8.   …    
  9. }    
  10.     
  11. // Candidate for C# 9    
  12. void DoSomething (string txt!)    
  13. {    
  14.   …    
  15. }   

Skip locals init

 
Allow specifying System.Runtime.CompilerServices.SkipLocalsInitAttribute as a way to tell the compiler to not emit localsinit flag. SkipLocalsInitiAttribute is added to CoreCLR.
The end result of this will be that the locals may not be zero-initialized by the JIT, which is, in most cases, unobservable in C#.
 
In addition to that stackalloc data will not be zero-initialized. That is observable but also is the most motivating scenario.
 

Lambda discard parameters

 
Allow the lambda to have multiple declarations of the parameters named _. In this case, the parameters are "discards" and are not usable inside the lambda.
 
Examples
  1. Func zero = (_,_) => 0;    
  2. (_,_) => 1, (intstring) => 1, void local(int , int);  

Attributes on local functions

 
The idea is to permit attributes to be part of the declaration of a local function.
 
“From discussion in LDM today (4/29/2019), this would help with async-iterator local functions that want to use [EnumeratorCancellation].
 
We should also test other attributes:“
 
[DoesNotReturn]
[DoesNotReturnIf(bool)]
[Disallow/Allow/Maybe/NotNull]
[Maybe/NotNullWhen(bool)]
[Obsolete]
 
Basic Example,
  1. static void Main(string[] args)    
  2. {    
  3.   static bool LocalFunc([NotNull] data)  
  4.   {    
  5.     return true;    
  6.   }    
  7. }  
The main use case for this feature,
 
Another example of using it with EnumeratorCancellation on the CancellationToken parameter of a local function implementing an async iterator, which is common when implementing query operators.
  1. public static IAsyncEnumerable Where(this IAsyncEnumerable source, Func predicate)      
  2. {      
  3.   if (source == null)      
  4.       throw new ArgumentNullException(nameof(source));      
  5.         
  6.   if (predicate == null)      
  7.       throw new ArgumentNullException(nameof(predicate));      
  8.       
  9.   return Core();      
  10.       
  11.   async IAsyncEnumerable<T> Core([EnumeratorCancellation] CancellationToken token = default)      
  12.   {      
  13.        await foreach (var item in source.WithCancellation(token))      
  14.        {      
  15.         if (predicate(item))      
  16.         {      
  17.             yield return item;      
  18.         }      
  19.        }      
  20.   }      
  21. }
Advanced Example here.
 

Native Ints

 
Introduces a new set of native types (nint, nuint) the ‘n’ for native. The design of the new data types is planned to allow a one C# source file to use 32 naturally- or 64-bit storage depending on the host platform type and the compilation settings.
 
Example
 
The native type is depending on the OS,
  1. nint nativeInt = 55; //take 4 bytes when I compile in 32 Bit host.    
  2. nint nativeInt = 55; //take 8 bytes when I compile in 64 Bit host with x64 compilation settings.  

Function pointers

 
I remember the term function pointer from C/C++. FP is a variable that stores the address of a function that can later be called through that function pointer. Function pointers can be invoked and passed arguments just as in a normal function call.
 
The proposal here.
 
One of the new C# candidate features is called Function Pointers. The C# function pointer allows for the declaration of function pointers using the func* syntax. It is similar to the syntax used by delegate declarations.
 
Example
  1. unsafe class Example    
  2. {    
  3.   void Example(Action<int> a, delegate*<intvoid> f)  
  4.   {    
  5.     a(42);    
  6.     f(42);    
  7.   }    
  8. }  
Enhancing Pattern Matching and More C# 9 stuff you can read in the following C# Preview article.
 
 

Summary

 
You have read about the candidates in C# 9 Feature Status, and I have demonstrated them to you.
C# NEXT feature List status is shown below, which at contains the worklist for C# 9. Only if the candidate features in the “master” branch, that means the feature will be released in the next version.
 
Import: a lot of things are still in discussions. The proposed features and syntax/semantics might be changed, or the feature itself might be changed or removed. Only .NET developers can decide which features will be released in C# 9 and when it will be released. In the next article, I will continue with the proposals.
 
When the C# 9 will be released, I will make for you a cheat sheet as in C# 7 and C# 8. You can follow me on GitHub or my home page.


Similar Articles