Using var or not using var [duplicate]
Possible Duplicate:
C# 'var' vs specific type performance
Hi all,
I recently saw code that usesvar
a lot.
E.g.:
var myString = GetAnyString();
var myInstance = GetClass();
instead of
string myString = GetAnyString();
MyClass myInstance = GetClass();
Besides the readability (I think that开发者_如何转开发 using var
is not very readable), are there any advantages and/or drawbacks using it? How about performance
It is subjective, but I don't like using vars. As for me they don't improve readability.
But general guideline on var
usage is following:
Use var
when it is absolutely clear what type of the variable is being declared:
Dictionary<string, Dictionary<string, string>> varOfSomeLongType = new Dictionary<string, Dictionary<string, string>>();
or when you are declaring variable of anonymous type:
var linqResult = from element in SomeCollection
select new { element.A, element.B }
var is replaced by the compiler with the right type, so there is no runtime performance hit, aside from a very small compile time overhead maybe (veeeeeeeery small).
Actually, from a readability point of vue, I personally do as follows:
Variable instantiation:
object myVar = new object();
Variable propagation:
var myVar = anotherVar.getComplexObject();
Also, you might be tempted to use them when you have a very complex type instantiation, like:
var myDict = new Dictionary<string, List<Tuple<string, object>>>();
Here, it really improves readability.
are there any advantages and/or drawbacks using it?
An advantage: less typing.
(I think that using var is not very readable)
I partially agree with this point.
It is less readable when you have var s = foo();
instead of string s = foo;
. In other cases it can be more readable.
How about performance
At runtime there is no difference. The compiler converts it into the same intermediate code as if you had explicitly stated the type.
精彩评论