Happy New ... C# 9 Features!

As one of my languages du jour, I've always had a fondness for C#. It was one of the first high-level languages that I learned in college and it's been part of my daily professional life for the better part of ten years. One of the things that's always been enjoyable about the language is the concept of constant innovation.
 
Features are constantly being adapted from other languages (looking at you F#, Kotlin, Typescript, and more) to help add features that would be greatly desired, extend existing functionality, or just apply an ample sprinkling of syntax sugar. So I thought with the new year just beginning, let's take a look at some of the proposed features that are slated to find their way into the flagship Microsoft language in the near future!
 
It's worth noting that this is by no means a complete list and everything in this list, as with all things in active development, is subject to change / never happen.
 
So, let's get into it!
 

Your Results May Covary

Have you ever been writing a class and found yourself just inventing new methods so that you can return some type from a base class since C# has always restricted you to only return the explicit class itself? This proposal outlines what would be support for covariant return types, which would allow you to override an existing method using a more specific implementation than the original method.
  1. class Animal    
  2. {  
  3.     virtual Animal GenerateFromEnvironment(EnvironmentConfiguration config);  
  4. }  
 
Now previously, if you wanted to extend your Animal class to support something like a Dinosaur, you'd have to either write some hacky bridge method or throw some logic in there to specifically check for the existence of a Dinosaur. Covariant returns will allow you to still override the same base class / methods, but return the more specific implementations you are looking for your class:
  1. class Dinosaur : Animal    
  2. {  
  3.     // Notice the more specific return type overriding the virtual method  
  4.     override Dinosaur GenerateFromEnvironment(EnvironmentConfiguration config);  
  5. }  
Support for this feature does not require the targeted class to implement the IDisposible interface, but instead just contain a Dispose() method.
 

A "New" New

Often the var keyword can be great if you don't want to go to the effort of explicitly defining a type for a variable. You already know what it's going to, so it's convenient to just keep things short. This proposal follows that same rough premise by introducing a new usage for the word 'new', specifically type targeted new expressions, which allows you to completely forego the type specification for constructors when the type is already know.
 
Let's say you had some complex collection like the following that you wanted to initialize upon declaration:
  1. Dictionary<string, List<string>> words = new Dictionary<string, List<string>>() {    
  2.     { "foo"new List<string>(){ "foo""bar""buzz" } }  
  3. };  
This proposal simplifies the use of new expressions since it already knows the types, so instead of using new Dictionary<string, List<string>>(), you can just use new()
  1. Dictionary<string, List<int>> words = new() {    
  2.     { "foo"new() { "foo""bar""buzz" } }  
  3. };  

Null Checks Kotlinified No More

 
No one really likes writing countless null checks. Lines upon lines of if statements with nested exceptions being thrown, it's gross. In a vein similar to the previous feature, this proposal aims to eliminate the need for explicit null checking by allowing an operator ! to be added to a parameter to indicate to the compiler that a given value will not be null.
 
It would transform a snippet like the following,
  1. // Before  
  2. int CountWords(string sentence)    
  3. {  
  4.     if (sentence is null)   
  5.     {  
  6.         throw new ArgumentNullException(nameof(sentence));  
  7.     }  
  8.   
  9.     // Omitted for brevity  
  10. }  
Into a much terser, uncluttered form,
  1. // Notice the trailing '!' after the parameter name, which indicates  
  2. // it will not be null  
  3. int CountWords(string sentence!)    
  4. {  
  5.     // Omitted for brevity  
  6. }  

Let the Constructor Do the Work

 
Another proposal that has been or in some phase of discussion since C# 6 has been the idea of primary constructors, a feature that's been found in languages like Typescript, Kotlin, and other languages. The basic idea behind primary constructors is that they would simplify writing class constructors and boilerplate code in general by implicitly creating private fields from the arguments passed in by the constructor itself.
 
Let's look at an example of a class with a few private, read-only properties,
  1. public class Widget    
  2. {  
  3.     private readonly int _foo;  
  4.     private readonly WidgetConfiguration _config;  
  5.   
  6.     public Widget(int foo, WidgetConfiguration config)  
  7.     {  
  8.          _foo = foo;  
  9.          _config = config;  
  10.     }  
  11. }  
The proposal would remove the need for the boilerplate field declarations as the constructor itself would handle creating the arguments passed in,
  1. public class Widget    
  2. {  
  3.      public Widget(int _foo, WidgetConfiguration _config)  
  4.      {  
  5.           // If you wanted one of these properties to be publicly accessible, you could define  
  6.           // and set one of those here, otherwise the arguments will be privately accessible  
  7.           // as fields.  
  8.      }  
  9. }  

If That Wasn't Simple Enough... How About Records?

 
If you enjoyed the last proposed feature, then you may find yourself doing a double-take with this one. Another proposal that has been toyed with for a while is the concept of records. Records are a simplified form for declaring classes and structs that supports some new features to simplify working with them (such as caller-receiver parameters and with expressions).
  1. public class Widget    
  2. {  
  3.     // Properties (business as usual)  
  4.     public readonly string Foo;  
  5.     public readonly string Bar;  
  6.   
  7.     // Definition of a With expression, which will allow you to easily create instances of a widget  
  8.     // from an existing instance  
  9.     public Widget With(string foo = this.Foo, string bar = this.Bar) => new Widget(foo, bar);  
  10. }  
We can see this demonstrated below,
  1. var existingWidget = new Widget("foo""bar");  
  2.   
  3. // Now create a brand new instance with one of the properties changed  
  4. var clonedWidget = existingWidget.With(bar: "buzz");  
  5.   
  6. // At this point clonedWidget looks like this: { Foo = "foo", Bar = "buzz" }  
Records will also support the use of positional pattern matching along with the use of destruction in tandem to do things like this,
  1. var widget = new Widget("foo""bar");  
  2.   
  3. // If the widget has a its Foo property set to "foo", then this condition will be met  
  4. if (widget is Widget("foo", var bar)) {    
  5.     // Perform some operation here on the widget, the use of var above will function as destruction so you can  
  6.     // access it within this scope  
  7.     Console.WriteLine(bar);   
  8. }  
Records are one of the more involved features being proposed in C# 9, so if you are curious or want to learn more about them, I'd highly recommend checking out the full proposal on them here, which contains a wide range of examples, use cases, and more.
 

Switching It Up ... Visual Basic Style?

 
One of the very few things that you'll see come up from a developer that has recently switched from Visual Basic to C# is the switch statement. Despite C# undergoing nearly nine entire revisions, support for comparison operations within switch statement was never supported (although pattern matching comes close), this proposal aims to remedy that.
  1. var internalTemperature = GetInternalTemp(yourDinner);    
  2. switch(internalTemperature)    
  3. {  
  4.     case <= 110:  
  5.         // Very rare  
  6.     case <= 125:  
  7.         // Rare  
  8.     case 125 to 135:  
  9.         // Perfect  
  10.     case <= 145:  
  11.         // Medium  
  12.     case <= 155:  
  13.         // What are you doing?  
  14.     case > 155:  
  15.         // What have you done...  
  16. }  

But Wait - There's More!

 
The features that were covered in this post are some of the more practical ones that might see everyday use, but these were by no means all of the currently proposals. I'd encourage you, if you are interested in learning more about what else might be on the menu at the related milestone for C# 9 on GitHub.
 
There you'll find tons of additional features that weren't mentioned here such as,
Finally - the C# language is open-source and is always looking for contributors, opinions, and any folks that love the language to share their thoughts on what could make it better.


Similar Articles