179

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?

Community
  • 1
  • 1
IAdapter
  • 62,595
  • 73
  • 179
  • 242
  • Other duplicates http://stackoverflow.com/questions/296783/resharper-vars http://stackoverflow.com/questions/1010480/why-does-resharper-default-to-warning-if-you-dont-declare-using-var http://stackoverflow.com/questions/1873873/why-does-resharper-want-to-use-var-for-everything http://stackoverflow.com/questions/1299045/is-resharper-correct – Erik Funkenbusch Feb 01 '11 at 22:10
  • -1 : This has been covered *so* many times before, and the duplicates are easily found by searching the site. – Greg Beech Feb 01 '11 at 22:12
  • 6
    @Greg Beech I disagree, not everybody knows its a ReSharper's bug, I thought it means something, but I was wrong. – IAdapter Feb 01 '11 at 22:14
  • Since you seem so hell bent on justifying your refusal to use the search engine and read any of the literally hundreds of previous questions that answer you, Here are Resharpers own reasons for doing this http://resharper.blogspot.com/2008/03/varification-using-implicitly-typed.html – Erik Funkenbusch Feb 01 '11 at 22:24
  • 2
    @Mystere Man funny link, they say "It removes code noise.", they do know a lot about make a useless noise. – IAdapter Feb 01 '11 at 22:40
  • http://www.infoq.com/news/2008/05/CSharp-var – NoWar Apr 02 '14 at 17:41
  • 1
    Since this is (wrongfully) marked duplicate I cannot add the following as answer: Keep in mind that there is one scenario where you MUST use var, and that's with anonymous types (introduced C#3), as this example from https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/anonymous-types shows: var productQuery = from prod in products select new { prod.Color, prod.Price }; foreach (var v in productQuery) { Console.WriteLine("Color={0}, Price={1}", v.Color, v.Price); } The second foreach must use a var, as the type name is not known. – Maverick Meerkat Jun 19 '18 at 17:12
  • 1
    As everyone has pointed out, the main benefit is simply readability. However, I'd also like to highlight the value of consistency throughout your code. If you start using an explicit type in your code, for example `List`, I would recommend sticking to it and not using `var` for the same type of object elsewhere. Again, this really just helps readability and understanding of your code if others are to read it. – devklick Mar 11 '19 at 21:05

4 Answers4

120

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

See also here for the performance question:

Community
  • 1
  • 1
Martin Buberl
  • 45,844
  • 25
  • 100
  • 144
  • 3
    That's correct. But I've tried to use var keyword in VS2010 but syntax auto completion seems to be puzzled sometimes. So maybe with ReShaper there is no drawback to use it. – Peposh Feb 01 '11 at 22:13
  • @Peposh yup.. same here that's why I stopped using it... until I started using ReSharper that is. – carny666 Mar 14 '14 at 15:18
  • 10
    I stopped using it as another generation of developers wouldn't stop complaining about it. My defense was if they had read and understood the code it didn't make any difference.I think it actually make things easier; if you refactor code and the types change you don't have to update your references to the whatever you've refactored if it changes types, ie less typing = less work. – user1040975 May 19 '16 at 17:56
  • 31
    For what it is worth, in my personal experience there is never a reason to use var. If you are do not know what type of is being returned from some function, that function needs to be refactored as it is clearly too difficult to understand. Any time that is saved by a developer on anything has to be picked up by another developer( usually a junior ) in the future, who has to spend more time figuring out what a piece of code actually does. – Alan Sep 15 '17 at 13:34
  • 2
    Only Codestyle? I don't agree: https://dotnetfiddle.net/FwpqlU – Max Mustermann Apr 10 '18 at 23:24
  • 11
    I don't agree with this point at all - the compiler may generate the same bytecode for both but from a code readability/maintenance point of view surely its better for variables to be clearly typed - it avoids ambiguity and makes it clearer to read and so understand. I found this post since I was also looking for answers to why ReSharper was wanting me to replace all my typed variables with var. I know modern languages are moving towards being un-typed and letting the compile decide even at run-time - but I have to say that I dont necessarily see this as a positive development. – robbie70 Aug 01 '18 at 14:28
  • 4
    Your totally correct Robbie, this has been creeping into C# since I first looked at it around 5 years ago, I only have occasional contact with C# these days, but when I do, and I want to look something up, I notice almost all documentation is using vars, meaning if you want deep understanding of a snippet with a view of implementing it in a different fashion, good luck. I have been fervently opposed to these kind of shortcuts since I started working with code. The seconds saved by not typing a variable named are invariably lost later by unreadable code. I have seen this countless times. – Alan Aug 10 '18 at 13:24
  • Actually there's another effect: not using var on instantiation or casting, causes the reference to appear twice when 'looking for all references'. Var doesn't hinder readability in that case (It improves it) and solves that issue. – Ori Nachum Apr 14 '20 at 16:45
  • 1
    What's interesting about some of these comments is it's as if we're using notepad to write code; if you are, well, good luck with that. If not, then simply put that funny little pointer you have over the variable and you can get its type. Same with a function; you can easily get its complete signature and overrides right there in your code. Do what keeps the code consistent and check your egos in the parking lot. – ChiefTwoPencils Jan 25 '22 at 15:43
  • @ChiefTwoPencils even then, if you can't read a line of code to determine the type of the lhs of an assignment operator, then it's either one of two things, 1) the code is (very) poorly written and should be refactored, or, 2) writing software is not your cup of tea and you should start looking for a different job. Like the compiler, I can infer the type of a variable by reading the line(s) assigning a value to it. I have no need for explicit types, unless I'm dealing with a dynamic object or non-generic code – Tom Lint May 30 '22 at 07:28
39

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

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 1
    there is a green warning, I think hint is when I click for example on string and I can do some magic with it, but this is a warning. After click on it its called "Suggestion". – IAdapter Feb 01 '11 at 22:11
  • 8
    @01: I wouldn't say a green light is a "warning". Orange or red, yes... but green? – Jon Skeet Feb 01 '11 at 22:16
  • if its a matter of coding style than why should I care about it? its a Suggestion, but for a new users like myself it looks like warning and if I did not care I would just change it to var(ReSharper should know better than me). I think the technical term is "noise". – IAdapter Feb 01 '11 at 22:18
  • 1
    @01: I suspect if you regard green lights as warnings you're going to find a lot of things like this... I don't think most new users would associate the colour green with a warning. You should care about it because coding style affects readability, but it's not like either style is necessarily "good" or "bad" - hence the green flag rather than orange or red. – Jon Skeet Feb 01 '11 at 22:20
  • @JonSkeet but do you really think var is a nice code style? MSDN documentation says explicitly, they don't use var in their examples because it makes the code less readable. Why is this a trend? I see everyone using type inferrence nowadays? For me this is really bad code style. Can you explain? – El Mac Apr 10 '16 at 17:43
  • 1
    @ElMac: It really depends on the context. I use it a lot more than I used to, particularly in tests. I don't use it where the type isn't obvious, but when calling constructors (for example) I would almost always use it - I find code *more* readable that way, particularly when you're using generic types. – Jon Skeet Apr 10 '16 at 17:50
  • 1
    " if you've already made the type of the variable crystal clear on the RHS of the assignment " Alas, I see this VERY rarely in people's code. Usually, I'll need to follow an assignment back to the definition of the RHS's identifier; a pain. – Glurth Jul 20 '16 at 18:59
  • @JonSkeet I'm reading _C# in Depth_ right now, and I came here looking for an answer to this exact question. I'm not surprised to see that you've left a response. Thanks for your thoughts on this! –  Sep 06 '16 at 13:44
  • 1
    As we generally read from left to right, it makes it easier if it is explicit on the LHS. It also has the added advantage of stopping you having to hover over RHS which are not explicit. I know that Jon has caveated his answer above, but explicit casting is the exception in code and not the norm. – davehay Jul 25 '20 at 09:44
  • _"I don't think most new users would associate the colour green with a warning"_ ...sure, if they're already familiar with official compiler warnings. For a new user, an IDE suggestion might seem like it's warning them that they're doing something wrong; thus it makes sense that they would call that suggestion a "warning". They don't realise it's only a suggestion because they're new. Suggestions are usually written in the form "do this", not "you have the option of doing this". "Do this" sounds like "it will be a problem if you don't do this" (which is warning of a potential mistake). – Clonkex Jul 26 '22 at 02:06
  • @Clonkex: The use of green as a generally "non-negative" indication (vs red as a negative one) is not a matter of being "familiar with official compiler warnings". This is a pretty global cultural color system IMO. – Jon Skeet Jul 26 '22 at 07:00
  • I don't think a newbie would consider that "green means good". They just see an indicator light. They inspect the light. The light warns them they're doing something wrong. In fact, the message even reinforces that "green isn't necessarily good". If it meant "good" or even "non-negative", it wouldn't be telling them they did something wrong. I don't know if you've worked with programming newbies before, but in my experience, you must immediately throw all your logic, reasoning and sensible assumptions out the window. To them, the light colour is irrelevant; only the message matters. – Clonkex Jul 26 '22 at 07:48
  • @Clonkex: I don't think it will be productive to discuss this further, and it's not really suitable for SO comments anyway. – Jon Skeet Jul 26 '22 at 07:52
20

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));
Alex Essilfie
  • 12,339
  • 9
  • 70
  • 108
  • 18
    The reason I would prefer NOT to use **var** is if I've made a mistake about the type I expect to be returned on the RHS, then using an explicit type on the left side will catch the mistake. Also it is not always obvious from looking at the RHS what the type is without Intellisense. In the example above I'd be inclined to add a using statement ` using NestedKVP = KeyValuePair> NestedKVP y1 = new NestedKVP("key", new KeyValuePAir("subkey", 5)); ` – JonN Mar 31 '14 at 23:55
16

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.

H H
  • 263,252
  • 30
  • 330
  • 514
  • 6
    but like many frameworks like this ReSharper is forcing his taste ;) – IAdapter Feb 01 '11 at 22:19
  • 7
    Resharper is not forcing anything. It's a suggestion. That's why it's green. – Erik Funkenbusch Feb 01 '11 at 22:25
  • @Mystere Man just like you are not forcing anybody to not agree with ReSharper, you are just saying that ReSharper is always right. I think most people see green warning. – IAdapter Feb 01 '11 at 22:43
  • 11
    @01 I didn't say Resharper is always right. Hell, I didn't express any opinion on this, right or wrong. Stop putting words in my mouth. I just said it's a suggestion, right or wrong, that's all it is. It's neither forcing anyone to do anything (forcing means that you have no choice, clearly you have the choice to ignore it, thus it's not forcing) nor is it a warning, as warnings are yellow in nearly every user interface known to man. – Erik Funkenbusch Feb 01 '11 at 22:52