DEV Community

Cover image for My Favorite New C# Feature: Target-Typed New
Matt Eland
Matt Eland

Posted on • Originally published at newdevsguide.com

My Favorite New C# Feature: Target-Typed New

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");
Enter fullscreen mode Exit fullscreen mode

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>();
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

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.

Latest comments (2)

Collapse
 
shimmer profile image
Brian Berns • Edited

As an F# guy, I'm really surprised that C# devs don't like var. This new new thing is OK, but var seems cleaner to me. Writing C# is often so tedious. Let the compiler worry about the types, at least!

Here's how these two declarations look in F#:

let author = Author("Matt Eland")
let playerGoals = Map.empty
Enter fullscreen mode Exit fullscreen mode

So much simpler.

Collapse
 
frederik_vl profile image
Frederik Van Lierde

I use it since day 1