Home > Software design >  Different ways to instantiate classes
Different ways to instantiate classes

Time:07-15

Aside from personal preference is there any difference between:

SomeClass SomeInstance = new SomeClass();

SomeClass SomeInstance = new();

and

var SomeInstance = new SomeClass();

CodePudding user response:

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://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-9.0/target-typed-new

  • Related