Thursday, November 12, 2020

C# 9.0: Target-typed new expressions

C# 9.0 is finally here along with .NET 5. Happy times.

In this post, let's have a look at a small but nice feature which can make some part of our code looks much nicer. 

In C#, all this time when you are using new expression, you needed to specify the type (which type you are going to be newing on) except when newing an array.  

// Type is required when newing
var person = new Person("John""Doe");
var fruits = new List<string>() { "Apple""Orange" };

// Except this one
int[] arrray = new[] { 1, 2, 3 };

With C# 9.0, you can do something like this.

Person person = new ("John""Doe");

List<string> fruits = new() { "Apple""Orange" };

Now instead of using implicit type on the left-hand side, we can be specific by putting the explicit type and then on the right-hand side when we are newing, we can omit the type. Because the compiler knows what type of object we are going to create based on the left-hand side.

It's really becoming handy when it comes to a more complex collection initializer. Consider the below Dictionary initializer.

var keyValuePairs = new Dictionary<intPerson>()
{     { 1, new Person("John""Doe") },
    { 2, new Person("Jane""Doe") }
};

With Target-typed new expressions,

Dictionary<intPerson> keyValuePairs = new ()
{
    { 1, new ("John""Doe") },
    { 2, new ("Jane""Doe") }
};

Isn't it pretty neat?

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment