Why does ReSharper want to use 'var' for everything?

C#.NetVisual StudioResharperVar

C# Problem Overview


I've just started using ReSharper with Visual Studio (after the many recommendations on SO). To try it out I opened up a recent ASP.NET MVC project. One of the first and most frequent things I've noticed it suggesting is to change most/all my explicit declarations to var instead. For example:

//From This:
MyObject foo = DB.MyObjects.SingleOrDefault(w => w.Id == 1);
//To This:
var foo = DB.MyObjects.SingleOrDefault(w => w.Id == 1);

and so on, even with simple types such as int, bool, etc.

Why is this being recommended? I don't come from a computer science or .NET background, having "fallen into" .NET development recently, so I'd really like to understand what's going on and whether it's of benefit or not.

C# Solutions


Solution 1 - C#

What ReSharper suggests is clearly overuse of the var keyword. You can use it where the type is obvious:

var obj = new SomeObject();

If the type is not obvious, you should rather write it out:

SomeObject obj = DB.SomeClass.GetObject(42);

Solution 2 - C#

One reason is improved readability. Which is better?

Dictionary<int, MyLongNamedObject> dictionary = new Dictionary<int, MyLongNamedObject>();

or

var dictionary = new Dictionary<int, MyLongNamedObject>();

Solution 3 - C#

I personally prefer to turn this suggestion off. Using var can often improve readability; but as you mentioned, it sometimes reduces it (with simple types, or when the resulting type is obscure).

I prefer to choose when I use var and when I don't. But again, that's just me.

Solution 4 - C#

var can increase readability of code while decreasing immediate comprehension of the code. Just the same, it can decrease readability of the code for other situations. Sometimes the use of it is neutral. The measure of readability to comprehension isn't proportional but depends on the situation. Sometimes both are increased or decreased together.

The factor is what var's being applied to and how well the target supports immediate obfuscation of its data type to the reader, or if its type info is needed to comprehend the program portion at hand.

For example, bad naming can to lead to var causing decrease of code comprehension. This is not var's fault though:

var value1 = GetNotObviousValue(); //What's the data type? 
//vs. 
var value2 = Math.Abs(-3); // Obviously a numeric data type. 

Sometimes it doesn't make sense to use var for simple data types when code is more readable in its absence:

var num = GetNumber(); // But what type of number?
// vs. 
double num = GetNumber(); // I see, it's a double type. 

Sometimes var can be useful to hide data type information that you don't necessarily care to see the complexities of:

    IEnumerable<KeyValuePair<string,List<Dictionary<int,bool>>>> q = from t in d where t.Key == null select t; // OMG! 
    //vs. 
    var q = from t in d where t.Key == null select t;

    // I simply want the first string, so the last version seems fine.  
    q.First().Key; 

You must use var when there's an anonymous type present because there's no type name to call it by:

var o = new { Num=3, Name="" };

When you have Visual Studio Intellisense providing type information in spite of var, you then need to rely less on your understanding via strict code reading without an aid. It's probably wise to assume not everybody may have or use Intellisense.

In summary based on the above examples, I'd suggest carte blanche application of var is not a good idea because most things are best done in moderation and based on the circumstance at hand as shown here.

Why does Resharper use it all over by default? I'd suggest for ease, because it can't parse the nuances of situations to decide when best not to use it.

Solution 5 - C#

In ReSharper (8.02, but likely other versions), the option for the "Use implicitly typed local variable declaration" suggestion can be adjusted to your preference, whatever that may be, by first opening the options menu for ReSharper:

ReSharper Options Menu

Then, under "Code Inspection" by adjusting the "Inspection Severity" of your chosen language, in my case c#:

Turn off implicitly typed local variable suggestion

As you can see, there are options to adjust all the suggestions that ReSharper makes. Hopes this helps someone like me who already has a 'var' usage strategy and just wants ReSharper to respect it :)

Solution 6 - C#

'var' is about being clear

The main debate about whether to use the var keyword or not is about how readable the code is to you and other developers.

Just as if you were writing a story there is not definitive right answer. But let's look at some examples of this in plain English.

> Jake said hello to Bill. He didn't like him so he turned and went the other way.

Who went the other way? Jake or Bill? In this case using the names "Jake" and "Bill" is like using the type name. And "He" and "him" is like using the var keyword. In this case it might help to be more specific. The following for example is much clearer.

> Jake said hello to Bill. Jake didn't like Bill so he turned and went the other way.

In this case being more specific made the sentence clearer. But that's not always going to be case. In some cases being specific makes it harder to read.

> Bill likes books, so Bill went to the library and Bill took out a book that Bill has always liked.

In this case it would be easier to read the sentence if we used "he" and in some cases left out his name all together, which is the equivalent of using the var keyword.

> Bill likes books, so he went to the library and took out a book that he has always liked.

Those examples cover the gist, but they don't tell the whole story. In those examples there was only one way to refer to the person. Either by using their name or by using a more general term like "he" and "him".

In the case of code we have 3 ways we to help add clarity. The type, the variable name, and the assignment. Take this line of code for example:

Person p = GetPerson();

The question now becomes is there enough information in that line of code to help you figure out what's going on?

What about the following line of code? Would you still know what p means in this case:

var p = GetPerson();

How about now:

var p = Get();

Or now:

var person = Get();

Or this one:

var t = GetPerson();

Or this:

var u = Person.Get();

Whether the keyword var works in a given scenario depends a lot on the context of the code, like how the variables, classes, and methods are named. It also depends on the complexity of the code and the rest of the code surrounding it.

Personally I like to use the var keyword it's more comprehensive to me most of the time. But I also tend to name my variables after the type so I'm not really losing any information.

That said sometimes depending on the context I make exceptions, such is the nature of anything complex, and software is nothing if not complex.

Solution 7 - C#

I am surprised that nobody mentioned that it is also easier to change the type of the instantiated object, because

AVeryLongTypeName myVariable = new AVeryLongTypeName( arguments );

is a form of repetition. If I want to change AVeryLongTypeName into one of its derived classes, I need only change this once when using var and still can access methods of the child classes.

Aside from that, the improved readability is an important point, but as others said, var should not be overused, so I think turning the hint off in Resharper is absolutely ok.

Solution 8 - C#

I disliked this as well.

I dont want this to turn into a debate on the use of var, it has its uses but should not be used everywhere.

The key thing to remember is ReSharper is configured to whatever coding standards you want.

Edit: https://stackoverflow.com/questions/737835/resharper-and-var

Solution 9 - C#

I see many correct answers, but missing the full one.

It is true that ReSharper overuses var by default. I think most people would agree with that. It is also easier to read when var is used and the type is obvious such as when you use a new statement. I saw one post that showed how to update inspection severity to only show hints for the use of var.

I had tried to comment on other posts first to add where to set these but didn't have the reputation for it. Apparently, I also didn't have the reputation to post my screenshot of the settings.

I will explain how to get there.

In Visual Studio > Main Menu > Resharper > Options > Code Editing > C# > Code Style > Var Usage in declarations

  • For built-in types Use explicit type
  • For simple types Use 'var' when evident
  • Elsewhere Use'var'

enter image description here

ReSharper help documentation: Code Syntax Style: Implicit/Explicit Typing ('var' Keyword) — Configure preferences of using 'var' keyword

Solution 10 - C#

My rule is this:

  • Are you declaring a primitive type (i.e. byte, char, string, int[], double?, decimal, etc.)? -> Use the type:

      string myStr = "foo";
      int[] myIntArray = [123, 456, 789];
      double? myDouble = 123.3;
    
  • Are you declaring a complex type (i.e. List<T>, Dictionary<T, T>, MyObj)? -> Use var:

      var myList = List<string>();
      var myDictionary = Dictionary<string, string>();
      var myObjInstance = new MyObj();
    

Solution 11 - C#

I'd just like to point that the use of "var" is recommended in the C# Coding Conventions

> when the type of the variable is obvious from the right side of the assignment, or when the precise type is not important

so that's probably why the tip is on by default in ReSharper. They also provide some cases where it would not improve readability right below in the same document.

Solution 12 - C#

ReSharper recommends var because it tends to unclutter object creation.

Compare these two examples:

StringBuilder bld = new StringBuilder();

var bld = new StringBuilder();

It's just a shorthand that is supposed to be easier to read.

I think it's fine when you create new objects explicitly with "new". In your example however, it might not be obvious if the classes were not named properly.

Solution 13 - C#

BTW, ReSharper draws a distinction between 'you might want to apply this suggestion to your code' and 'your code is broken, want me to fix it?'. The var keyword is in the suggestion category, along with things like "invert if to reduce nesting"; you don't have to follow it.

You can configure how annoying each of its alerts are through the Options dialog, or directly through the popup menu for that alert. You can downgrade things like the var suggestion so they're less prominent, or you can upgrade things like the 'use extension method' alert so it shows up as an actual error.

Solution 14 - C#

The var feature of .NET 3.0 is just type inference, which is type-safe and often makes your code easier to read. But you don't have to, and can turn that recommendation off in ReSharper if you want.

Solution 15 - C#

Var is amazing! I have come across many a developer who are under the impression that var is bound to a dynamic type, it is not. It is still statically typed, it's just decided by the compiler.

Here are some amazing positives of using var

Less typing var is shorter and easier to read, for instance

Dictionary<int,IList<string>> postcodes = new Dictionary<int,IList<string>>() Yuk.

var postcodes = new Dictionary<int,IList<string>>() \o/\o/

More descriptive variable names - tenuous one but I think its important to let the fluid nature of var shine here. As var is a bit vague, it really does encourage a more desciptive variable name rather than letting the type speak for itself.

Less code changes - if the return type of a method call changes. You only have to change the method call, not every place it’s used.

Anonymous types - anonymous types are a really powerful concept, especially in areas such as WebApi partial resources. Without var, they cannot be used.

Sometimes however it is useful to explictly declare types and I find this most useful in primitives or structs. For instance, I don't personally find this syntax very useful:

for(var i = 0; i < 10; i++) 
{

}

vs

for(int i = 0; i < 10; i++) 
{

}

It's all down to personal preference but using var really will speed up your development and unlock a whole world of anonymous type goodness.

Solution 16 - C#

In my view, var should only be used when it is immediately clear what the type is when defining the value of the variable.

Example:

var s = "string value";

It is obvious that s is a string.

I believe it is also appropriate when the variable type name is very complex.

Example:

Dictionary<SomeCustomKeyType, Dictionary<AnotherCustomKeyType, List<int>>> dict = new Dictionary<SomeCustomKeyType, Dictionary<AnotherCustomKeyType, List<int>>>();

// This is a little easier to read than the above statement
var dict = new Dictionary<SomeCustomKeyType, Dictionary<AnotherCustomKeyType, List<int>>>();

Other than these scenarios, I don't see any GAIN to be made by using var, but I can think of some scenarios in which it can be detrimental:

For example, a disposable type whose right-hand-side variable value does not clearly show the type. Disposing of the IDisposable can easily be forgotten about

Example:

// returns some file writer
var wr = GetWriter();

wr.add("stuff");
wr.add("more stuff");

//...
//...

// Now `wr` needs to be disposed, 
// but there is no clear indication of the type of `wr`,
// so it will be easily overlooked by code writer and code reviewer.

Solution 17 - C#

There is no technical difference, if you use var, the type is implied by the compiler. If you have a code like this:

var x = 1;

x is implied to be an int and no other values can be assigned to it.

The var keyword is useful if you change the type of the variable; you then only have to make one change instead of two:

var x = 1; --> var x = "hello";
int x = 1; --> string x = "hello";

Solution 18 - C#

The var keyword was introduced in C# 3.0 - it allows us to forget about specifying our type explicitly.

There is no real difference to whether you use

MyObject foo = DB.MyObjects.SingleOrDefault(w => w.Id == 1);

or

var foo = DB.MyObjects.SingleOrDefault(w => w.Id == 1);

except pure readability and less chance for error.

It seems like a clichéd example, but say the following may help your understanding:

var myInt = 23;

returns an int type, whereas

var myInt = "23";

returns a string type.

MSDN reference

Solution 19 - C#

Specifying an explicit object type is somehow redundant. Even translated in english, the it sounds redundant: "put an object of type X in a variable of type X" vs "Put an object of type X in a variable".

However, using 'var' has its limitations. It prevents the below usage of polymorphism which is pure beauty:

Assume an Dog extends Animal; Cat extends Animal class hierarchy:

Animal x = new Dog();
DoStuffWithDog(x as Dog);

x = new Cat();
DoStuffWithCat(x as Cat);

void DoStuffWithDog(Dog d){}
void DoStuffWithCat(Cat c){}

The same code, with x declared with 'var' will not compile.

var x = new Dog(); // from this point, x is a Dog
DoStuffWithDog(x as Dog);

x = new Cat(); // cannot assign a Cat instance to a Dog
DoStuffWithCat(x as Cat);

void DoStuffWithDog(Dog d){}
void DoStuffWithCat(Cat c){}

Anyways, back to the original question, I don't use Resharper, but I assume that is is smart enough to detect when to not use 'var'. :-)

Solution 20 - C#

For those that dislike the constant use of "var", you can also stop ReSharper from defaulting to var when doing "introduce variable". This was something that frustrated me for a long time, it was always defaulting to var, and I was changing it every time.

These settings are under Code Editing > C# > Code Style

enter image description here

Solution 21 - C#

'var' adds a kind of "dynamic" element to your code (although the code remains of course strictly typed). I advice against using it in cases where the type is not clear. Consider this example:

var bar = GetTheObjectFromDatabase();
bar.DoSomething();

ClassA {
  void DoSomething() {
  //does something
  }
}

ClassB {
  void DoSomething() {
  //does something entirely different
  }
}

Should the return Type of GetTheObjectFromDatabase() be changed from Type A to B we will not notice, since both Classes implement DoSomething(). The code, however, may now actually do something entirely different.

This may be as subtle as both writing different stuff to a log, so you might not notice unitl it's too late.

The following use of var should always be fine:

var abc = new Something();

Solution 22 - C#

There is no technical difference (as eWolf pointed out). You can use one or the other, the generated CLR code will look the same.

In my opinion the main benefit is that this tends to force you to use better variable naming. In your example 'foo' is a pretty poor choice for a variable name.

Solution 23 - C#

According to JetBrains (the author of ReSharper), they encourage the use of var by default.

From their website: > Using implicitly typed local variables (also known as var keyword) introduced in C# 3.0 has become quite popular as it improves readability in many scenarios. By default, ReSharper also encourages using of var keyword, but preferences of its usage are flexibly configurable — for example, you can opt for using explicit types in specific cases or everywhere and ReSharper will help you enforce your preferences.

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
QuestionChrisView Question on Stackoverflow
Solution 1 - C#GuffaView Answer on Stackoverflow
Solution 2 - C#Mark SherrettaView Answer on Stackoverflow
Solution 3 - C#Bryan MenardView Answer on Stackoverflow
Solution 4 - C#John KView Answer on Stackoverflow
Solution 5 - C#ErikestView Answer on Stackoverflow
Solution 6 - C#Luis PerezView Answer on Stackoverflow
Solution 7 - C#PhilippView Answer on Stackoverflow
Solution 8 - C#LiamBView Answer on Stackoverflow
Solution 9 - C#Nathan KovacView Answer on Stackoverflow
Solution 10 - C#Sumner EvansView Answer on Stackoverflow
Solution 11 - C#joseView Answer on Stackoverflow
Solution 12 - C#Paul SasikView Answer on Stackoverflow
Solution 13 - C#Tim RobinsonView Answer on Stackoverflow
Solution 14 - C#Klaus Byskov PedersenView Answer on Stackoverflow
Solution 15 - C#KnowHoperView Answer on Stackoverflow
Solution 16 - C#James WierzbaView Answer on Stackoverflow
Solution 17 - C#eWolfView Answer on Stackoverflow
Solution 18 - C#Daniel MayView Answer on Stackoverflow
Solution 19 - C#xtremView Answer on Stackoverflow
Solution 20 - C#DerekView Answer on Stackoverflow
Solution 21 - C#lolaldaneeView Answer on Stackoverflow
Solution 22 - C#Jaco PretoriusView Answer on Stackoverflow
Solution 23 - C#Jeff ReddyView Answer on Stackoverflow