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

后端 未结 8 2050
南方客
南方客 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:31

    No. Use var where it improves readability and vice versa.

    0 讨论(0)
  • 2021-01-02 04:35

    In general no technical reason. Readability - in either direction - is the only real factor.

    However, one small caveat is that var will infer the static type of the variable. If you want a sub or super class type you'll need to do the casting yourself. In the case of a foreach, as in your example, you can usually get downcasting performed for you "for free" just by declaring your loop variable with the subclass type.

    The classic example is iterating over an XML NodeList that you know is a list of XmlElement, but Nodelist is typed as a collection of XmlNodes. Of course you can use a cast or an as to get back the type you want, but that would seem to defeat the purpose of using type inference :-)

    Of course, the compiler will let you know about this as soon as you try to use a member of the node that is only available to XmlElement - so it's still not strictly a technical difference.


    Another thing that is a little annoying is that if you use a tool like Resharper, it's very aggressive about suggesting you use var in every possible situation. It's particularly annoying when it recommends you change, for example, an int declaration into a var!

    However, unless you turn that feature off, you'll get less "noise" from Resharper the more you use var.

    0 讨论(0)
提交回复
热议问题