开发者

Using var or not using var [duplicate]

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

Possible Duplicate:

C# 'var' vs specific type performance

Hi all,

I recently saw code that uses var 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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜