top of page

Target-typed new() expressions in C# 9

“Target typing” is a term used for when an expression gets its type from the context of where it’s being used. In C# 9.0 some expressions that weren’t previously target typed become able to be guided by their context.

We all know that when we want to create a new object we need to use ‘new’ keyword plus specifying the target type as below:

User objUser = new User();

this syntax is fine but there is a simple question here. I have already declared that I am going to create an object of type User by saying: User objUser` so why do I need to use new User()` again?

In this situation where the target type in known we can rewrite the code as below:

User objUser = new();

Now we have target-typed the ‘new’ expression! Please note that target typing the ‘new’ expression works only when we explicitly specify the type, obviously when we are using the var` to create an object, target typing has no meaning. As an instance, the following code will NOT work:

var objUser = new();//Error: There is no target type for 'new()'

If we takes a look back to C# we can find out that similar behavior was already in C# for implicitly typed array expressions where we were able to construct an array as below:

var myArray = new []{1, 2, 3};

Ok now, lets take a look at this feature from other perspective too. Do you remember the var` keyword and its usage? Great, when we can omit the Type, is there any difference to omit it from left side or right side of an expression? lets take a look these two expressions:

User objUser1 = new();
var objUser2 = new User();

At first look it seems a waste of time to think about the target-typed new() expression. But is this true and is this the whole story? For sure NO. why? Suppose that you are going to define a field of a class. Can you use var` to define a field in a class? No :-) In fact var` is useful when we are going to define a local variable.

What the compiler thinks about the var` and target-typed new() ? The compiler will generate the exact same IL code for both the var` and target-typed new expression . In our example the compiler will generate the following IL code after compilation:

User objUser1 = new User();
User objUSer2 = new User();

Source: Medium - Vahid Farahmandian

The Tech Platform

bottom of page