Why should I use var instead of a type?

C#.NetCoding StyleResharperVar

C# Problem Overview


> 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 prefer var? better performance? anything? or is it just a code style?

C# Solutions


Solution 1 - C#

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

See also here for the performance question:

Solution 2 - C#

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 :)

Solution 3 - C#

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));

Solution 4 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIAdapterView Question on Stackoverflow
Solution 1 - C#Martin BuberlView Answer on Stackoverflow
Solution 2 - C#Jon SkeetView Answer on Stackoverflow
Solution 3 - C#Alex EssilfieView Answer on Stackoverflow
Solution 4 - C#Henk HoltermanView Answer on Stackoverflow