开发者

What is the purpose of 'var'? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

What's the point of the var keyword?

I'm not asking how it works. I am not asking if it affects performance. I already know those answers.

I want to know what inspired the MS C# team to add it to the language in the first place. You don't add frivolous things to a language. There must have been a noteworthy problem it solved. What was/is that problem?

The closest example I've seen to "the problem it solves" is when using anonymous types, like this:

var linqResult = from element in SomeCollection s
                 elect new { element.A, element.B } 

The irony about this usage is that style and coding-standards guides (such as provided by Microsoft) advise the coder to avoid using 'var' when the resulting type is not obvious. In other words, the (presumably) intended purpo开发者_如何学Pythonse of 'var' is in conflict with the coding-standard guidelines.

If I were writing coding-standards, and was trying to prevent overuse of 'var', I'd be somewhat inclined to say "use 'var' only in response to anonymous types." But that brings the question full-circle: what was/is the purpose of having added 'var' to the language?


Anonymous Types was the big one, but also reducing repetition within methods:

Dictionary<MyCustomType, List<MyOtherCustomType>> dict = new Dictionary<MyCustomType, List<MyOtherCustomType>>();


Exactly! Anonymous types. How in the world would you keep a reference to a created anonymous type if there was no var and still have intellisense along with it?

In other words: When there was no var, there wouldn't be any anonymous types in the usable sense we have now with compile time support. There would be just too many runtime errors with anonymous types.

The added sugar (of complexity when overused) is that you can use var with even non-anonymous variables. Sure it works but it's a bad habit.


As far as I know the var keyword was made pretty much to make LINQ easierby enabling the use of anonymous types


From MSDN:

In many cases the use of var is optional and is just a syntactic convenience. However, when a variable is initialized with an anonymous type you must declare the variable as var if you need to access the properties of the object at a later point. This is a common scenario in LINQ query expressions.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜