230

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.

2
  • 6
  • 28
    I've been thinking about this for a while and I came to conclusion that I should always use var, even when the type is not obvious at all! the reason is because it forces me to choose the most descriptive name I can come up with and ultimately that makes the code much, much more readable. Ultimately it also helps to separate the logic from the implementation. Of course that's just my opinion, I hope it would help someone ;). Jan 30, 2013 at 9:45

23 Answers 23

298

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);
16
  • 40
    To play devils advocate, maybe if the type is not clear from the method or the variable name, it indicates a problem with naming more then an overuse of var. I do agree in principal though, var should only be used when it is not removing clarity. Dec 9, 2009 at 13:40
  • 36
    In this instance I would rather use better variable names. You are basically proposing that we look up to see where the variable is defined to figure out the type - I am proposing that we name the variables better so that we know the purpose of the variable offhand. Dec 9, 2009 at 13:41
  • 20
    @Jaco: +1, but it's worth to mention that information about type is not recommended to be in a variable name. For example, Hungarian notation is not considered to be a good practice. Dec 9, 2009 at 13:55
  • 8
    Whether ReSharper's default settings are an overuse of var is a matter of opinion, and not "clearly" one thing or another. I prefer not to type things that the compiler can figure out for itself. I like C# type inference, and often wish it was as good as F# type inference. If I could, I'd leave out explicit types from method parameters and return types, as is the norm in F#. Not everyone agrees, of course. Dec 9, 2009 at 17:25
  • 15
    @AnonymousType: You are still missing the point. You said that method names should always reflect the intention of the method, but even if they do that doesn't mean that the name specifies the type of the return value. The method for reading from a Stream object for example is named Read, not ReadAndReturnNumberOfBytesAsInt32.
    – Guffa
    Jan 29, 2013 at 8:26
204

One reason is improved readability. Which is better?

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

or

var dictionary = new Dictionary<int, MyLongNamedObject>();
22
  • 280
    I would say the first one. Easier to see whats going on! Dec 9, 2009 at 13:30
  • 122
    Fungus: Do you like Do you like Redundant Text Redundant Text? :D Dec 9, 2009 at 13:32
  • 78
    Being explicit is more clear in my opinion. Using var to much creates a headache in some scenarios. Jan 9, 2012 at 15:43
  • 182
    I hate it when developers use var for everything - I do lots and lots of code reviews using TFS (web based diffs) and it makes my job extremely difficult: i.e. var items = GetSomeItems(); vs IDataReader dr = GetSomeItems(); Missing using statement on both but easier for me to catch when using IDataReader vs var. Mar 3, 2013 at 10:54
  • 22
    if you're a good developer writing good code, and you're using a library like Resharper, then you don't need to know the explicit type that your dealing with. Just as when you use interfaces to declare a contract, but not a concrete class, var allows you say that you don't care what the return "type" is, you only care what it does, and using well-named variables, along with intelli-sense & resharper / VS helpers (such as CTRL+CLICK to navigate to definition) will get you 99% of the way there. Additionally, using var means I don't have to rewrite my code-base if I change a method return type. Nov 9, 2013 at 20:55
101

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.

4
  • 11
    I thought ReSharper was meant to be pretty smart; Shouldn't it be smart enough to know when the resulting type is obvious (e.g. anything with the new keyword) and when it is not obvious? Dec 9, 2009 at 13:42
  • 3
    Well, I don't know the peculiarities of the feature but, I sure know I was overwhelmed by the amount of suggestions it gave; And I use var fairly often too. Dec 9, 2009 at 13:48
  • 6
    I found out that when you always use var (like resharper suggest), it force you to name your variables properly.
    – Sauleil
    Jan 28, 2011 at 13:46
  • @AngeDeLaMort: the point is that it forces you to use names which are improper, f.e. var methodXYResultIntArray. That's against all coding standards and less concise than int[] methodXYResult. If you want to return a byte[] from the method in future all your variable names are wrong. With explicit types you could refactor this very easily. There are reasons to use var, f.e. with a Dictionary<string, List<SomeType<int>>>. But if the full-type-name is not too long and you don't use new on the right side (or an explicit cast) resharper should not suggest it. Jan 18, 2017 at 8:47
69

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.

4
  • 5
    IMHO your examples are actually good reasons to use var, it will force you to write decent method names. GetNumber() -but what type?- well, why do you care? If it's that important to know, call the method GetNumberAsDouble(), then it's just as clear and will work if you have one method returning string and one returning double. Feb 3, 2015 at 22:37
  • 10
    @nicodemus13 You generally know when you care about the return type of a function when you actually use the return value rather than when you are writing the function itself. Your suggested naming scheme could lead to abuse like GetResultsAsIEnumerableOfDouble and it all it does is shift the type information you removed from the left side of an assignment by using var to the right side of the assignemnt.
    – Eric
    Jul 7, 2015 at 20:58
  • var value2 = Math.Abs(-3); // Obviously a numeric data type. Sorry I disagree on this one, completely, given that the Abs method has 7 overloads that leads to nothing but obscurity when looking at it, imo
    – s1cart3r
    Mar 8, 2018 at 8:52
  • var can also lead to subtle logic errors like: var counter = "0"; when what you want is an integer.
    – alaniane
    Aug 5, 2019 at 20:59
42

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

2
  • This answers a different question that wasn't asked at all. Jan 2, 2017 at 4:20
  • 9
    But it's relevant to many who look for it when getting here. +1
    – Ori Nachum
    Jan 22, 2017 at 8:57
28

'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.

2
  • 1
    I like this answer the best, because I have nothing against var as long as I know what it is while reading that one line. If I have no idea what a method from another Solution using a different domain model is returning, I rather have that type explicitly defined, making it much easier to read. +1
    – Piotr Kula
    Jul 26, 2016 at 17:26
  • In all of your cases where the type returned is not evident I agree you should not use var as you are now omitting useful information.
    – rollsch
    Nov 22, 2016 at 4:26
24

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.

2
  • Very useful when calling factory methods rather then "new" Mar 17, 2015 at 9:37
  • If you need to use 'MyClass' when you initially write the code and it works, then it works. When you need to change it, you have to go and change it everywhere, especially when you have interfaces involved. Code shouldn't be treated like an essay, it should be semantic and well defined.
    – Piotr Kula
    Jul 26, 2016 at 17:16
18

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: ReSharper and var

1
  • 15
    After a year or so resisting, I pretty much always use var now.
    – LiamB
    Jul 23, 2013 at 12:36
16

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

3
13

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();
    
1
  • I'd like to disagree, string myStr = "foo"; is obvious it's a string. I'd put all your examples in the use the var category... and declarations that are returns from a method to use the explicity type. But at the end of the day, it's whatever you and your team feel is better for the particular project. Apr 5, 2018 at 14:45
12

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.

2
  • That is great when you know that the type comes from System.Diagnostics.PerformanceCounter() - You can easily tell its the perfomance counter from the built in diagnostics class. But what type is returned here? var thingyMaBob = GetThatSpecialThing(18,null,(MyEnum)2) ? No clocking clue, especially if you have well over 100 projects in your solution.
    – Piotr Kula
    Jul 26, 2016 at 17:18
  • "Recommended when the type of the variable is obvious", and "They also provide some cases where it would not improve readability right below in the same document". Honestly, I think I've missed your point. My answer says the same thing you say.
    – jose
    Jul 27, 2016 at 13:01
6

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.

1
  • It is useful in the above scenario, but not in cases like foreach (var item in collection) Nov 7, 2020 at 12:00
6

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.

5

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.

4

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.

3

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.
2

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";
2
  • 1
    @AlexKamburov the code 10 lines below will break anyway, is not related to var. Apr 8, 2015 at 14:42
  • 1
    @user3285954 In some cases var can hide the problem and that's when things could get ugly. The problem is not in writing code, the problem is in maintainability. Some argue it's cleaner with var but I see it sometimes as obfuscation. It's close to a religious debate. brad-smith.info/blog/archives/336 I personally use var only for Linq statements and other places where declaring the type is really verbose. I think var is a good addition and people need to watch Anders Hejlsberg's comments on the reasons for introducing it. Apr 9, 2015 at 15:11
2

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

2

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

8
  • 4
    Needless casting (with as) is pure awful. You turn compile errors into runtime errors if you have something like Animal x = new Cat(); DoStuffWithDog(x as Dog); Why reuse x? Dog x = new Dog(), Cat y = new Cat(), boom no more possible ambiguity.
    – Mark Sowul
    Dec 5, 2013 at 15:46
  • casting (with 'as' or not) could result in a run time error. What is so 'awful' about casting when you know what you are doing? Why reuse x? The example here is illustrative. The goal of the example is to show how using 'var' can result in limitations when a reference is meant to be polymorphic.
    – xtrem
    Jan 19, 2014 at 20:18
  • 5
    No, it can't: polymorphism is the opposite of what is going on here. This is trying to pass objects of type Animal into methods that take Dog and Cat. Polymorphism is the reverse: so you can pass objects of type Dog and Cat into a method that takes Animal, for example void Walk(Animal a): Walk(new Cat()), Walk(new Dog())
    – Mark Sowul
    Jan 31, 2014 at 2:44
  • You shouldn't reuse variables this way, leads to very nasty bugs. Not so obvious in short methods but when you have 15-20 lines of code you will forget what x is. Don't be lazy: var dog = new Dog(); DoStuff(dog); var cat = new Cat(); DoStuff(cat); Apr 8, 2015 at 15:00
  • 2
    No fight. I don't have feelings for either ways of declaring variables (implicit or explicit). I actually use at least one of each most days. I am simply highlighting that when you chose the implicit (var) method, the compiler will decide the narrowest possible type for you. Which may not always be what you want. That's all.
    – xtrem
    Apr 10, 2015 at 19:11
1

'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();
1

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

0

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.

0

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.

1
  • Where can I configure when to require explicit type declaration?
    – user764754
    Nov 23, 2017 at 16:49

Not the answer you're looking for? Browse other questions tagged or ask your own question.