Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between new() and new class() C#

What is the difference between new() and new class() because it seems that both run with no difference.

Human John = new();

or

Human John = new Human();

Let's say in this context it does not make any difference, could anyone provide an example of which both cases would result in different outputs for each code. Thanks!

like image 798
Dane Avatar asked Sep 07 '25 17:09

Dane


1 Answers

You ask about the difference between new() and new class(). It is unclear what class is referring to. Which class?

If it can be any class, then a trivial situation where new() and new class() would produce different outputs is when class is a derived class of the type you are assigning it to. object x = new(); would create an instance of object, and object x = new StringBuilder(); would create a new StringBuilder.

If you mean class must be the same as the type that you are assigning to, then a situation where new() and new class() would produce different outputs is when you are assigning to a nullable type.

int? x = new(); // same as int? x = 0;
int? x = new int?(); // same as int? x = null;

Because the target type in this case is the non-nullable int type.

Also note that sometimes the type you are assigning to cannot be instantiated with the syntax new class() - such as when it is an interface, abstract class, array type, etc. In these cases, new() also won't work.

There are also situations where new() just won't compile, but new class() would, for some class. e.g. var x = new();, SomeGenericMethod(new()) where SomeGenericMethod needs the type of the first parameter to infer a type parameter. These don't work because the compiler can't figure out what type new() should instantiate. See also an interesting case in this question.

Learn more about new(), aka target-typed new expression, in the draft spec.

like image 108
Sweeper Avatar answered Sep 10 '25 08:09

Sweeper