C# Var vs Target-typed new
Asked Answered
T

1

8

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(),
}
Trimble answered 21/5, 2020 at 17:19 Comment(3)
What do you mean by performance, its a compiler feature, does not have any runtime implicationsEustatius
I doubt there's any real difference in terms of the IL generatedCrossruff
@MatJ Everything I found online about var was comparing it to explicitly-typed declarations, or requesting that it be allowed on member declarations. This C#9 syntax is quite new, so I figured I'd ask the question. I also don't know everything about how compilers work, so I didnt know if it had runtime implicationsTrimble
D
8

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.

Delocalize answered 21/5, 2020 at 17:30 Comment(2)
Thanks @Giorgi! I didnt know if there was any difference in the IL generated. I think I'm personally liking var for single variables cause then all declarations can line up on the left, and target-typed new for collections so there's less repetition.Trimble
Target typed new is especially useful for class-level fields that include generics. Like private readonly Dictionary<string, SomeLongTypeName> _dict = new Dictionary<string, SomeLongTypeName>(); versus private readonly Dictionary<string, SomeLongTypeName> _dict = new();Barmy

© 2022 - 2024 — McMap. All rights reserved.