Search code examples
c#constructornew-operatorvar

Different ways to instantiate classes


Aside from personal preference is there any difference between:

SomeClass SomeInstance = new SomeClass();

SomeClass SomeInstance = new();

and

var SomeInstance = new SomeClass();

Solution

  • new() was introduced in C#9 for use with type inference so you don't have to keep specifying it if the type is already known. Example is if you are creating a

    new List<Something>() { new Something()}

    then each new Something() can be changed to new()

    new List<Something>() { new()}

    thus less syntax :)

    The Microsoft release doc is here to explain it better than i could. https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-9.0/target-typed-new