Is there any technical reason to use or not to use var in C# when the type is known?

后端 未结 8 2121
南方客
南方客 2021-01-02 04:05

It seems that more and more C# code I read uses the var type identifier:

foreach (var itemChange in ItemChanges)
{
   //... 
}
8条回答
  •  萌比男神i
    2021-01-02 04:19

    There is no technical reason. If the type cannot be inferred at compile time then the code will not compile.

    You are right in stating there are instances where it may be better to use an explicit type for readabilty, e.g.

    var obj = SomeMethod(); // what's the type? you'd have to inspect SomeMethod()
    SomeClass obj = SomeMethod(); // the type is obvious
    

    but other instances where using var makes perfect sense, e.g.

    var obj = new SomeClass(); // the type is obvious
    SomeClass obj = new SomeClass(); // the duplication of type is unnecessary
    

提交回复
热议问题