Possible Duplicate:
What’s the point of the var keyword?
What is the var
type and should it be used in c#? When should it be used?
Can you specify the var type for the parameters to a method?
var is not a type. It is a convinient short hand notation that saves you a lot of typing. The following two declarations are equivalent:
Dictionary<string,List<int>> dic = new Dictionary<string,List<int>>();
and
var dic = new Dictionary<string,List<int>>();
As you can see, this saves typing and are easier to read. And if you descide to change the data type, you only have to change the right hand part.
But where I really like it most is in foreach loops:
foreach ( var item in someList )
Here item automatically takes the correct type, depending on the type of someList and it enables you to change the type of someList without haveing to change the declaration of item.
In short: var is GREAT and should be used.
EDIT: No, you can not specify var as a parameter to a function. The closest you can get to that is generics, I guess. And I also completely forgot to mention anonymous types. With those you have to use var.
It is part of the language, so yes, it should be used. It is not a type, however, but signifies a placeholder for the actual type determined by the compiler.
When should you use it? This has been asked before, many times:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With