Cody  Osinski

Cody Osinski

1625160540

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:

?

1

2

3

4

class Preferences

{

private List<string> _favoriteColors = new List<string>();

}

From C## 9 you can instead write:

?

1

2

3

4

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.

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:

?

1

2

3

4

5

6

7

8

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:

?

1

2

var prefs = new Preferences();           

prefs.DisplayColors(new DisplayOptions());

With C## 9 you can simplify this to:

?

1

2

var prefs = new Preferences();

prefs.DisplayColors(new());

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

?

1

2

Preferences prefs = new();

prefs.DisplayColors(new());

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

?

1

2

3

4

class DisplayOptions

{

public string Title { get; init; }

}

?

1

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.

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