开发者

Why should I use var instead of a type? [duplicate]

开发者 https://www.devze.com 2023-02-08 12:46 出处:网络
This question already has answers here: Closed 12 years ago. Possible Duplicate: ReSharper and var After I have installed ReSharper it demands(by warnings) that I use var whenever possib
This question already has answers here: Closed 12 years ago.

Possible Duplicate:

ReSharper and var

After I have installed ReSharper it demands(by warnings) that I use var whenever possible, for example

UnhandledExceptionEventArgs ue = (UnhandledExceptionEventArgs) t;

ReSharper wants to turn it into

var ue = (UnhandledExceptionEventArgs) t;

I like the first version better, is there any reason to pref开发者_高级运维er var? better performance? anything? or is it just a code style?


It's really just a coding style. The compiler generates the exact same for both variants.

See also here for the performance question:

  • Will using 'var' affect performance?


When you say "by warnings" what exactly do you mean? I've usually seen it giving a hint that you may want to use var, but nothing as harsh as a warning.

There's no performance difference with var - the code is compiled to the same IL. The potential benefit is in readability - if you've already made the type of the variable crystal clear on the RHS of the assignment (e.g. via a cast or a constructor call), where's the benefit of also having it on the LHS? It's a personal preference though.

If you don't want R# suggesting the use of var, just change the options. One thing about ReSharper: it's very configurable :)


As the others have said, there is no difference in the compiled code (IL) when you use either of the following:

var x1 = new object();
object x2 = new object;

I suppose Resharper warns you because it is [in my opinion] easier to read the first example than the second. Besides, what's the need to repeat the name of the type twice?

Consider the following and you'll get what I mean:

KeyValuePair<string, KeyValuePair<string, int>> y1 = new KeyValuePair<string, KeyValuePair<string, int>>("key", new KeyValuePair<string, int>("subkey", 5));

It's way easier to read this instead:

var y2 = new KeyValuePair<string, KeyValuePair<string, int>>("key", new KeyValuePair<string, int>("subkey", 5));


In this case it is just coding style.

Use of var is only necessary when dealing with anonymous types.
In other situations it's a matter of taste.

0

精彩评论

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