ICYMI C# 9 New Features: Reducing Code with Target-typed New Expressions

This is part of a series of articles on new features introduced in C# 9.

C# 9 introduced some enhancements to reduce the amount of code you need when creating new instances of objects.These target-typed new expressions “Do not require type specification for constructors when the type is known.” [MS]

As an example in C# 8 with fields you need to explicitly create an instance:

class Preferences
{
    private List<string> _favoriteColors = new List<string>();
}

From C# 9 you can instead write:

class Preferences
{
    private List<string> _favoriteColors = new();
}

Notice in the preceding code you can simply write new() because the target type is known to be List<string>.

If you are calling a method (or constructor) that requires an instance of an object, you can also use new(). For example suppose you had the following method that requires a DisplayOptions instance:

public void DisplayColors(DisplayOptions options)
{
    Console.WriteLine(options.Title);
    foreach (var color in _favoriteColors)
    {
        Console.WriteLine(color);
    }
}

Prior to C# 9, if you wanted to just create a new instance of DisplayOptions and pass it in you would write:

var prefs = new Preferences();            
prefs.DisplayColors(new DisplayOptions());

With C# 9 you can simplify this to:

var prefs = new Preferences();
prefs.DisplayColors(new());

You could also write this using a target-typed new expression for the Preferences instance:

Preferences prefs = new();
prefs.DisplayColors(new());

If you have init only properties you can also use target-typed new expressions:

class DisplayOptions
{
    public string Title { get; init; }
}
DisplayOptions options = new() { Title = "Colors" };

If you want to fill in the gaps in your C# knowledge be sure to check out my C# Tips and Traps training course from Pluralsight – get started with a free trial.

SHARE:

Comments (1) -

  • Ken Bonny

    6/28/2021 11:42:24 AM | Reply

    It also works with non empty constructors. So the `new()` is a shorthand to get to all constructors, not just the default one. 🙂

Add comment

Loading