Target Typed New Expressions

Back in the old days, declaring variables and instantiating objects made for some pretty lengthy and ugly code:

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

Then came "var", which let you declare a variable and it would be strongly typed to be whatever the right side of the equals sign says it is. This made things much better:

var result = new List<string>(); // result is of type List<string>

In scenarios where you needed your variable to be of a base class or interface type, you'd still do things the old fashioned way, but for a lot of simple code, var was a game changer. However, var is occasionally abused, where it's not obvious what the right-side type is - in those scenarios, I prefer opting for skipping var.

var something = GetSomething(); // What type is this variable? Don't know unless you follow it in the IDE.

Something something = GetSomething(); // Better

Now there's target typed new expressions, which go a step farther.

Foo foo = new();
// equivalent to:
Foo foo = new Foo();

You're declaring the variable type, and the compiler figures out which class's constructor you're using because it's pretty obvious. You can even use it when creating a new object as an argument in a method. You can't use this everywhere of course - if you want your variable to be an interface or base class type, you can't do it, and if the argument in the method is ambiguous, you won't be able to either.

void Go(Foo foo) { }
void Go2(Foo foo) { }
void Go2(Bar bar) { }

Go(new()); // It knows this must be a Foo
Go2(new()); // This won't compile because it's ambiguous

Object intialization and collection initialization use this new syntax as well, making things like a Dictionary much more compact:

// parenthesis are required, otherwise it would think it's an anonymous type
Foo foo = new() { Message = "Hello" }; 

Dictionary<int, string> = new()
{
    { 3, "three" },
    { 4, "four" }
};

View code on GitHub

Comments

Popular posts from this blog

C# Record Serialization

Add timestamp to photo using ImageMagick

Read/write large blob to SQL Server from C#