|For local variables, it's not necessary to repeat the type name:
var - C# Reference | Microsoft Docs[^]
Implicitly typed local variables - C# Programming Guide | Microsoft Docs[^]
The following two lines produce identical IL:
Animal fox = new Animal();
var fox = new Animal();
NB: You can't use
var for fields, property types, method parameters, or return types.
Why no var on fields? – Fabulous Adventures In Coding[^]
There is a suggestion which would allow fields declared as:
Animal fox = new();, but it hasn't been implemented yet:
csharplang/target-typed-new.md at master · dotnet/csharplang · GitHub[^]
NB2: Some people vehemently oppose any use of
var beyond anonymous types. And it certainly can be overused - for example,
var x = Foo(); would compile, but is not readable. But for a
new expression, where the type is right next to the variable declaration, I don't see any problem with using
NB3: To clarify, based on the responses: using
new expressions is fine; you should generally avoid it for anything else.
var x = new SomeType(); is fine.
var x = SomeMethod(); is bad.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
modified 16-May-19 9:45am.
General News Suggestion Question Bug Answer Joke Praise Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
Copyright © CodeProject
All Rights Reserved.