Search code examples
c#varvariable-declaration

C# Var vs Target-typed new


C#9 was officially announced a couple days ago. One new language features is "target-typed new expressions", which feel pretty similar in usage to var. Comparing the following declarations, I'm curious which is more performant, if any, and which syntax should be preferred for different contexts.

var person = new Person() vs Person person = new().

And for collections:

var people = new[] {
    new Person(),
    new Person(),
    new Person(),
}

vs

var people = new Person[] {
    new(),
    new(),
    new(),
}

Solution

  • var person = new Person() and Person person = new() will compile to the same IL code. They are just 2 different ways to tell the compiler which type to initialize; they do not have anything to do with runtime performance.