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

后端 未结 8 2048
南方客
南方客 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条回答
  •  时光说笑
    2021-01-02 04:16

    var is a C# 3.0 feature only mandatory in anonymous type

    Because following code

    var v = new { Amount = 108, Message = "Hello" };
    

    dynamically create a new anonymous type, var usage is mandatory. For example, var is particularly useful in Linq where type are often created dynamically.

    In any other situations, it's only a matter of taste for final application (it's resolved during compilation). But for code readers, I think 'var' is less informative that type itself.

提交回复
热议问题