In the previous blog posts you learned about different C## 9.0 features:
In this blog post, let’s look at another very interesting feature of C## 9.0 that is called target-typed **new**
expressions.
Target-typed means that an expression gets the type from the context it is used in. With C## 9.0 the new
expression gets the type from the context, which means you don’t have to specify the target-type explicitly to call a constructor. Let’s look at this with a simple example.
Let’s define the Friend
class that you see in the code snippet below. As you can see, it has a default constructor and also a constructor with the parameters firstName
and lastName
to initialize the properties FirstName
and LastName
.
public class Friend
{
public Friend() { }
public Friend(string firstName, string lastName)
{
FirstName = firstName;
LastName = lastName;
}
public string FirstName { get; set; }
public string LastName { get; set; }
}
To create a new instance of this Friend
class, you can use this statement:
Friend friend = new Friend();
You can also use the constructor overload to pass in a firstname and a lastname:
Friend friend = new Friend("Thomas", "Huber");
As the variable gets initialized directly with a new Friend
, you can also use the var
keyword for the variable declaration like below. The C## compiler detects in this case the type Friend
for the variable, as you assign a new Friend
instance to it. The var
keyword was introduced in 2007 with C## 3.0 and .NET Framework 3.5, and it works for local variables.
var friend = new Friend("Thomas", "Huber");
Now, in all those cases above you can see that the new
expression – that’s the part on the right side of the =
sign – always requires the class name. That’s not the case anymore with C## 9.0 if the target-type is already known from the left side of the =
sign, which is always the case if you don’t use the var
keyword on the left side of the =
sign.
With C## 9.0 you can create a new Friend
like below with the target-typed new
expression to call the default constructor. Note that I don’t specify the Friend
class on the right side of the =
sign, the compiler gets it from the left side of the =
sign:
Friend friend = new();
You can also call the overloaded constructor of the Friend
class by passing in a firstname and a lastname:
Friend friend = new("Thomas", "Huber");
But, of course, you can not use the target-typed new
expression when you use the var
keyword to declare your variable, because then the compiler does not have a chance to find out the type that you want to create. So, the following statement does not work:
var friend = new("Thomas", "Huber"); // does NOT work
#.net #c# #c++