Home > dotnet > My Favorite New C# Feature: Target-Typed New

My Favorite New C# Feature: Target-Typed New

How I happily removed 95% of all var statements from my C# code

by
Published: Last Updated on

C# 9 added the "Target-typed new" keyword, which is a little bit of a mouthful, but a powerful feature for simplifying your C# code.

In this article we'll look at what the target-typed new keyword gives us and explore why I like it so much, especially compared to the var keyword.

Before we get into target-typed new, we need to understand the problem it tries to solve and the weaknesses of the previous solution to this problem.

The Problem We're Trying to Solve

Target-typed new is one of the new language features added to C# 9 in its release in fall of 2020. To explain what target-typed new does, let's look at a pair of example variable declarations in C#:

// Standard object instantiation
Article article = new Article("My Favorite New C# Feature: Target-Typed New");

// Using var
var author = new Author("Matt Eland");

Here we have to either repeat the Type we are declaring on the left or the right (as shown on line 2 above), or use the var keyword to simplify the assignment operation.

In this particular case, var isn't particularly helpful, but it can be very helpful when declaring more complex types such as dictionaries as shown below:

Dictionary<string, int> playerGoals = new Dictionary<string, int>();

var playerMinutesOnIce = new Dictionary<string, double>();

Here we see that var lets you simplify Dictionary initialization by removing duplicate "noise" from the code.

However, var can also obscure the Type something holds as shown below:

var result = CalculateResult();

Assuming that CalculateResult() is a valid C# method that returns some type of result, the code above is valid and correct. However, a casual reader might have difficulty determining if result stores a bool, an int, a string, or some other type without relying on tooltips or similar features of their IDE.

Because of this, var is often discouraged in codebases, but it still has benefits in some situations including simplifying object initialization and some more advanced language scenarios.

Introducing Target-Typed New

Target-typed new is a new language feature introduced in C# 9 in late 2020 that allows us to simplify our initialization using a new use of the new keyword:

Author author = new("Matt Eland"); // Note: Author not repeated for the constructor

Dictionary<string, int> playerGoals = new();

Both of these lines of code include the Type that we are ultimately working with and do not repeat it on the right when we are instantiating our object. Both of these lines remain readable without having to repeat Type information when it's not needed.

Frankly, I love this.

I love the way that this keeps the code readable without being repetitive, and I really like the use of the word new in this context.

Death to Var! Except not quite.

So are we done with var in C#?

Well, no, not quite. The var keyword still has a number of uses.

The main place I continue to use the var keyword is within foreach loops as shown below.

foreach (var item in items)
{
   Console.WriteLine(item);
}

I like var inside of foreach because I have found from experience that when I use the concrete Type in a foreach loop and later change the Type that my collection contains, the foreach will also need to be changed to the new Type. However, if I use var in a foreach loop, the new type is correctly inferred without me needing to make changes.

The other remaining uses for var involve dynamic programming and using var's late-binding features. However, these uses are a little too advanced for this article.

Final Thoughts on Target-Typed New

As with any new language feature in C#, the target-typed new keyword is optional. It represents another choice you can use to simplify your code on object initialization.

I really like target-typed new and so my articles and code feature it, but your mileage may vary.

Finally, I should point out that using the target-typed new keyword slightly increases the learning burden on your team. For experienced developers this isn't a big problem because the volume of new things they're learning is lower. However, with a new developer, this is just one more thing they need to understand and know when to use and not use.

Whenever you add any new language feature, ask yourself what language features are you taking away, if any. You should also consider what expectations you have for your team for learning this slightly different syntax and internalizing when to use it instead of the traditional way.

I'd love to hear what you and your teams standards are on initializing objects in C#. Do you use target-typed new? var? Inline-initializers? Traditional constructor calls? I'd love to hear what works for you and your team - and what you avoid.

Author

  • Matt Eland
    Microsoft MVP in AI, Professional Programming Instructor

    After several decades as a software engineer and engineering manager, Matt now serves as a software engineering instructor and gets to raise up future developers and unleash them upon the world to build awesome things. Matt is a Microsoft MVP in Artificial Intelligence, runs several blogs and channels on data science and software engineering topics, is currently pursuing a master's degree in data analytics, and helps organize the Central Ohio .NET Developer Group while contributing to local and regional conferences. In his copious amounts of spare time, Matt continues to build nerdy things and looks for ways to share them with the larger community.

    View all posts

3 comments

What are Generics in C#? November 2, 2022 - 4:22 pm

[…] For example, the code below creates a new instance of our LastItemTracker class that will manage string instances using the target-typed new keyword: […]

Reply
Introducing the C# 11 Required Keyword November 13, 2022 - 1:56 pm

[…] the new() syntax here is using the target-typed new feature introduced in C# 9 and is not strictly necessary for this example. The code could also have […]

Reply
Towards a Beginner-Friendly DotNet November 22, 2022 - 4:30 pm

[…] with C#’s target-typed new keyword this use case is no longer my recommendation and I instead recommend the following […]

Reply

Leave a Reply

Related Content

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More