In my last post I wrote about some cool features of C#9. You can find that post here. However while looking through the list I found some other cool ones. So here is another post with them.

Target typed new expressions
In the book clean code a couple of guidelines were written about naming things when programming. A name should tell something about:
1) Why it exsists
2) What it does
3) How it is used.

The book also states that long descriptive names are preferred over short ones. Using this we get long class and variable names, with one problem.. it causes us a lot of repeating when writing code. In C#9 a new syntax can be used for constructors. Consider the following example:

public class CustomerModelValidator
    private AdressValidator _addressValicator;
    private CreditCardValidator _creditCardValidator;
    public bool IsValid()
    public CustomerModelValidator()
        _addressValicator = new();
        _creditCardValidator = new();

The ‘new’ statements here are new (see what I did there…?). So instead of writing ‘_addressValidator = new AddressValidor()’. I can just use '_addressValidator = new()'

Covariant Returns

Sometimes when overriding an abstract method you have to cast the result of the method to actually use it. However in C# 9 the following is supported:

abstract class Animal
public abstract Food GetFood();
class Tiger : Animal
public override Meat GetFood() => …;

Top level programs
Usually when I want a quick prototype of a feature I normally switch to Linqpad. I can then write a simple program because it can generate the basic Main loop and stuff for me. With C#9 you can replace this:

using System;
class Program
    static void Main()

With this:

Using System;


This will save me a ton of plumbing when writing simple programs.

Leave a Reply

Your email address will not be published. Required fields are marked *