Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 purpose 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?

like image 394
Brent Arias Avatar asked Feb 16 '11 18:02

Brent Arias


People also ask

What is the purpose of the var keyword?

var is a keyword, it is used to declare an implicit type variable, that specifies the type of a variable based on initial value.

Why do we need VAR in JavaScript?

Variable means anything that can vary. In JavaScript, a variable stores the data value that can be changed later on. Use the reserved keyword var to declare a variable in JavaScript.

What is the meaning of VAR in JavaScript?

Definition and Usage The var statement declares a variable. Variables are containers for storing information. Creating a variable in JavaScript is called "declaring" a variable: var carName; After the declaration, the variable is empty (it has no value).

Can we duplicate a variable name using VAR and let keyword?

Assuming strict mode, var will let you re-declare the same variable in the same scope. On the other hand, let will not.


1 Answers

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

Dictionary<MyCustomType, List<MyOtherCustomType>> dict = new Dictionary<MyCustomType, List<MyOtherCustomType>>();
like image 119
Michael Stum Avatar answered Sep 28 '22 09:09

Michael Stum