Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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();

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading