231

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.

MasterMastic
  • 20,711
  • 12
  • 68
  • 90
Chris
  • 6,568
  • 3
  • 22
  • 21
  • 6
    Also - http://stackoverflow.com/questions/737835/resharper-and-var – LiamB Dec 09 '09 at 13:34
  • 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 ;). – MasterMastic Jan 30 '13 at 09:45

23 Answers23

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);
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • 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. – Matt Briggs Dec 09 '09 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. – Jaco Pretorius Dec 09 '09 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. – Roman Boiko Dec 09 '09 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. – Joel Mueller Dec 09 '09 at 17:25
  • I disagree with this example, if you have renamed the method to GetSpecificTypeName you would not have the readibility problem. If you really need a method that returns a generic object type, then the cast to the left of the method will still show the correct type information. In both cases the type used on the LHS of the code line will be easily inferred from best practise coding on the RHS. – Anonymous Type Jan 28 '13 at 23:47
  • 6
    @AnonymousType: The guidelines discourages type names in identifiers. Do you really suggest that you write the type name in a cast on the RHS just to avoid writing it on the LHS? What would be the benefit of that? – Guffa Jan 29 '13 at 00:28
  • I think you are misinterpreting the guidelines. I'm certainly not suggesting you EVER add an unnecessary cast, this would be bad design. Method names should ALWAYS reflect the intend of the function. If the intend is to return an object then GetObject would suffice. If the intend is to return a specific type, then why would you obsfucate the method name by calling it GetObject? – Anonymous Type Jan 29 '13 at 00:41
  • 6
    @AnonymousType: I think that you are missing the point entirely. Values doesn't always come from methods, and when they do it might be a framework method that you can't rename. You simply can't always write code where the type of the the result is obvious. – Guffa Jan 29 '13 at 01:35
  • mate please backup your arguments with assertions. I never implied values only come from methods, clearly that is NOT true. Of course you would not rename a framework method, but then if you are calling GetObject, var will be ... an Object! if it isn't you'll use a cast on the RHS which will make it real obvious on the LHS. so far all you have done is agreed with me. If the framework method is returning a value type well then its a pretty limited subset of types before you even look at the line of code. – Anonymous Type Jan 29 '13 at 04:43
  • 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 '13 at 08:26
  • 2
    +1 as I agree here. Some more examples: A `Count` property or method will *usually* return an `int`, but depending on the situation, there's nothing to say against returning another integer type, without cluttering the name. Members returning `bool` are supposedly an easy case, yet it could be perfectly fine to sometimes return a `bool?`. Working with different libraries sometimes means using different, equivalent types (e.g. something named `Rect` and something named `Rectangle`) at a time, either of which might be returned by something called `Bounds`. – O. R. Mapper Mar 28 '14 at 15:40
  • 2
    -1. 'clearly' is purely subjective. I hold the opposite view. Using `var` as much as possible avoids the crutch of needing to know the concrete type. It virtual prohibits refactoring, as it's a pain to redefine the return type all over the place. To me this is far more important than spurious 'clarity'. Anything that encourages refactoring. – nicodemus13 Feb 03 '15 at 22:31
  • 5
    @nicodemus13: Reading code that uses `var` everywhere is a pain. You have to track the code back all the time to see what's happening. If you really want to use it for refactoring, then you also have to treat every variable declared with `var` as a truly unknown type that you can't use where any specific type is needed. As soon as you treat the variable as a specific type, then you are not independent of the type any more. Changing the return type of a method is what's called a breaking change, and it's normal for the calling code to have to change. – Guffa Feb 03 '15 at 22:41
  • 4
    @Guffa- I find the opposite, having explicit types littered around the code for me is just distracting, ugly noise and gets in the way enormously. I don't see how knowing the explicit type really helps understanding what the code is intended to achieve, I'm not sure how reading type definitions helps the semantics. Where it may be a breaking change, but it's still easier to fix a few places where it will no longer compile, than have to change dozens of declarations for no positive reason. Still, there's a lot of opinion around `var`. – nicodemus13 Feb 03 '15 at 22:54
  • 5
    I've actually [raised a bug](https://youtrack.jetbrains.com/issue/RSRP-431885) on resharper regarding always pushing for var as it makes code harder to read and is at odds with the MSDN recs. With the suggestion of not pushing it if the type name doesn't appear on the right of the equals. So far it is assigned and not been rejected. – Vdex Mar 02 '15 at 21:25
  • This should be the answer. [C# Coding Conventions (C# Programming Guide) - Implicitly Typed Local Variables](https://msdn.microsoft.com/en-us/library/ff926074.aspx): `Use implicit typing for local variables when the type of the variable is obvious from the right side of the assignment, or when the precise type is not important.`. – MJVC Aug 26 '16 at 19:22
204

One reason is improved readability. Which is better?

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

or

var dictionary = new Dictionary<int, MyLongNamedObject>();
Mark Sherretta
  • 10,160
  • 4
  • 37
  • 42
  • 282
    I would say the first one. Easier to see whats going on! – Mongus Pong Dec 09 '09 at 13:30
  • 122
    Fungus: Do you like Do you like Redundant Text Redundant Text? :D – Mark Simpson Dec 09 '09 at 13:32
  • 4
    Thanks. Consensus seems to indicate it's just a readability suggestion, rather than being of benefit at compile time. – Chris Dec 09 '09 at 13:40
  • 8
    @Chris, exactly that. It makes no difference at compile/runtime, it's there for readability and (primarily) for supporting anonymous types, I believe. =) – Rob Dec 09 '09 at 13:49
  • 8
    @Fungus: add also a comment to make it absolutely clear: declaring the 'dictionary' variable of type 'Dictionary':) – Kamarey Dec 09 '09 at 14:03
  • 78
    Being explicit is more clear in my opinion. Using var to much creates a headache in some scenarios. – user1231231412 Jan 09 '12 at 15:43
  • 2
    @user1231231412: I agree on simple types, but with complex long types like `Dictionary` types with additional types for key and content, it is often just confusing (and gives me headache) to declaring explicitly. Especially in this example when creating a new object, where the type is specified in use of the `new` operator anyway. – awe Sep 07 '12 at 06:49
  • 6
    var is an implicitly typed local variable (strongly typed just as if you had declared the type yourself) - however - the compiler determines the type - not you! This means that the var keyword was not created for plain readability/redundant text removel. Also - using the var keyword does not clarify the actual type being used. – Henry Aloni Sep 26 '12 at 08:47
  • 183
    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`. – Chris Gessler Mar 03 '13 at 10:54
  • 3
    @ChrisGessler I agree with this, and mentioned this in my own answer to an [old deleted question here](http://stackoverflow.com/a/633768/57477) (you'll need 10K+ rep to see this deleted question unfortunately - but I've put the text of my answer [here](https://gist.github.com/anonymous/5450899)). var is great, but when used with a function call that returns a non-obvious type, explicit typing should be used IMHO. – CraigTP Apr 24 '13 at 09:23
  • 5
    I only use var when it's clear what the resulting type is. Yes, you can use VS to tell you by hovering, but it's not instantly obvious. For example, I would use var here: `var someNumber = 2000;` but not here: `var items = GetSomeItems();` as Guffa states below. – trousyt May 02 '13 at 14:54
  • var iDontKnowWhatTypeThisIs = SomeClass.SomeMethod(blah); // turn this into a linq statement – Chris S Jul 19 '13 at 22:28
  • 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. – Joshua Barker Nov 09 '13 at 20:55
  • 11
    I agree with Chris Gessler, and I think `var someNumber = 2000` is one of the worst uses of it because 2000 is semantically ambiguous. Yes, it will be an int, but you could assign 2000 to a float, a short, a long, etc. And `var` vs. `int` **saves no typing** to boot. – Mark Sowul Dec 05 '13 at 15:42
  • 4
    I'll say it again, it doesn't matter what TYPE i'm returning, but what that type represents from a domain perspective, and if I'm following good naming conventions, then the concrete type is entirely redundant. – Joshua Barker Feb 04 '14 at 16:32
  • 7
    It should be noted that the [guidelines on MSDN](http://msdn.microsoft.com/en-us/library/ff926074.aspx) say that "Do not use var when the type is not apparent from the right side of the assignment.", and that [MSDN](http://msdn.microsoft.com/en-us/library/bb384061.aspx) states "However, the use of var does have at least the potential to make your code more difficult to understand for other developers. For that reason, the C# documentation generally uses var only when it is required." as its own internal guideline. – O. R. Mapper Mar 28 '14 at 15:28
  • @HenryAloni: The compiler deterministically figures out the type, and unless the developer is randomly writing code without knowing what they are doing, that usually means the *developer* determines the type (and doesn't write it, because the compiler will figure out itself). Then, exactly because the compiler can figure out the intended type on its own, the `var` keyword serves for removing redundant text and (in some situations) improving readability. I don't see how you come to your conclusion that it does not - what was it actually created for, in your opinion? – O. R. Mapper Mar 28 '14 at 15:34
  • 5
    @O.R.Mapper - `var` was created to support LINQ and anonymous types, period. That it can be used to shorten code and improve readability is a lucky coincidence. – Davor Aug 24 '14 at 13:55
  • 1
    Resharper itself says "The var keyword is fairly controversial in terms of usage and any advice to use var in code is, by definition, opinionated." https://confluence.jetbrains.com/display/ReSharper/Use+%27var%27+keyword+when+initializer+explicitly+declares+type – Danish May 05 '15 at 07:19
  • 1
    I think `var` should be used only when the type of the variable can be easily inferred like when using the `new` operator or when using other trivial variable assignments (`int a; var b = a;`). It should be avoided for returning variables like in `var myObject = CreateMyObject();` as it's not clear what's the type of myObject. – Gianluca Ghettini May 29 '15 at 09:42
  • IMHO writing `Dictionary dictionary = new Dictionary();` is like saying I need a white basket with capacity of 5 liters and a handle. Please fill my white basket with capacity of 5 liters by 5 liters of water versus `var dictionary = new Dictionary();` is like saying please give me a white basket of 5 liters with a handle filled by water. I suggest reading this [nice article by Eric Lippert](https://blogs.msdn.microsoft.com/ericlippert/2011/04/20/uses-and-misuses-of-implicit-typing/) – Reza Nov 09 '16 at 11:02
  • Type safety - One of the strengths of a language like c# is that it is strongly typed. Overuse of var obscures that type safety. There are times when it is necessary to use it, but when it is not, and when the type is not immediately obvious, using var is as bad as using "r" for a variable name. You are hiding semantically significant, very important information from the reader, unnecessarily. –  Mar 21 '18 at 13:56
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.

Bryan Menard
  • 13,234
  • 4
  • 31
  • 47
  • 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? – DisgruntledGoat Dec 09 '09 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. – Bryan Menard Dec 09 '09 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 '11 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>>`. 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. – Tim Schmelter Jan 18 '17 at 08: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.

John K
  • 28,441
  • 31
  • 139
  • 229
  • 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`. – nicodemus13 Feb 03 '15 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 07 '15 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 08 '18 at 08:52
  • var can also lead to subtle logic errors like: var counter = "0"; when what you want is an integer. – alaniane Aug 05 '19 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 :)

Pang
  • 9,564
  • 146
  • 81
  • 122
Erikest
  • 4,997
  • 2
  • 25
  • 37
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.

Luis Perez
  • 27,650
  • 10
  • 79
  • 80
  • 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 '16 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 '16 at 04: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.

Philipp
  • 11,549
  • 8
  • 66
  • 126
  • Very useful when calling factory methods rather then "new" – Ian Ringrose Mar 17 '15 at 09: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 '16 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

Community
  • 1
  • 1
LiamB
  • 18,243
  • 19
  • 75
  • 116
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

Pang
  • 9,564
  • 146
  • 81
  • 122
Nathan Kovac
  • 231
  • 2
  • 4
  • This should be marked as the correct answer outside of var debates, this is the balanced approach – Brian Ogden Nov 11 '16 at 20:06
  • Could you give an example on how "where evident" is decided? – rollsch Nov 22 '16 at 04:25
  • [Use 'var' when evident: what is considered evident?](https://www.jetbrains.com/help/resharper/Using_var_Keyword_in_Declarations.html#use-var-when-evident-details) – Pang Jun 17 '20 at 00:15
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();
    
Sumner Evans
  • 8,951
  • 5
  • 30
  • 47
  • 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. – Dean Meehan Apr 05 '18 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.

Pang
  • 9,564
  • 146
  • 81
  • 122
jose
  • 637
  • 6
  • 20
  • 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 '16 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 '16 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.

Pang
  • 9,564
  • 146
  • 81
  • 122
Paul Sasik
  • 79,492
  • 20
  • 149
  • 189
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.

Pang
  • 9,564
  • 146
  • 81
  • 122
Tim Robinson
  • 53,480
  • 10
  • 121
  • 138
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.

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Klaus Byskov Pedersen
  • 117,245
  • 29
  • 183
  • 222
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.

KnowHoper
  • 4,352
  • 3
  • 39
  • 54
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.
James Wierzba
  • 16,176
  • 14
  • 79
  • 120
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'. :-)

xtrem
  • 1,737
  • 12
  • 13
  • 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 05 '13 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 '14 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 '14 at 02: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); – user3285954 Apr 08 '15 at 15:00
  • @MarkSowul, What is going on here is certainly a form of polymorphism. You are looking at the wrong place. The x variable (of type Animal) is polymorphic because it can hold references of different types (Cat and Dog or any other Animal). The example illustrates a side effect of the fact that using 'var' automatically confers the variable being declared the narrowest possible type (Cat or Dog), rather than something broader (like Animal) which can be useful sometimes. – xtrem Apr 09 '15 at 17:24
  • @user3285954, The code sample is simply and solely to demonstrate that the usage of 'var' prevents things that are possible when doing an explicit type declaration. – xtrem Apr 09 '15 at 17:30
  • There's a reason why the language is fighting you – Mark Sowul Apr 09 '15 at 22:08
  • 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 '15 at 19:11
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";
eflorico
  • 3,589
  • 2
  • 30
  • 41
  • 1
    @AlexKamburov the code 10 lines below will break anyway, is not related to var. – user3285954 Apr 08 '15 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. http://www.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. – Alex Kamburov Apr 09 '15 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

Daniel May
  • 8,156
  • 1
  • 33
  • 43
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

Pang
  • 9,564
  • 146
  • 81
  • 122
Derek
  • 7,615
  • 5
  • 33
  • 58
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();
lolaldanee
  • 23
  • 7
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.

Jaco Pretorius
  • 24,380
  • 11
  • 62
  • 94
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.

Pang
  • 9,564
  • 146
  • 81
  • 122
Jeff Reddy
  • 5,551
  • 9
  • 55
  • 88