53

Possible Duplicate:
Why does ReSharper want to use 'var' for everything?

I have ReSharper 4.5 and have found it invaluable so far but I have a concern;
It seems to want to make every variable declaration implicit (var).
As a relatively new developer, how much should I trust ReSharper when it comes to this?

Take the below code snippet from a method that Paints Tab Headers.

TabPage currentTab = tabCaseNotes.TabPages[e.Index];
Rectangle itemRect = tabCaseNotes.GetTabRect(e.Index);
SolidBrush fillBrush = new SolidBrush(Color.Linen);
SolidBrush textBrush = new SolidBrush(Color.Black);
StringFormat sf = new StringFormat
{
    Alignment = StringAlignment.Center,
    LineAlignment = StringAlignment.Center
};

Resharper wants me to change all 5 of those to var. I have read the following similar post, Use of var keyword in C#, but I would like to know from a ReSharper standpoint.

Community
  • 1
  • 1
Refracted Paladin
  • 11,636
  • 32
  • 115
  • 224

7 Answers7

44

Resharper is primarily concerned with helping you refactor code, and the var keyword generally makes refactoring easier. For example, if the return values of any of those functions ever change to a compatibile type, you don't have to change any of this code. It's therefore now a little easier to refactor your tabCaseNotes type, for example.

Personally, I'm often inclined to leave your first two lines alone, because I like to see the type name for a variable explicitly listed somewhere on the line where the variable is declared. If anything, I might look for an interface to use instead, so that I also gain the same "generic-ness" as with the var keyword without losing any important readable type information. However, I would definitely use var for fillBrush, textBrush, and sf.

Joel Coehoorn
  • 362,140
  • 107
  • 528
  • 764
  • 3
    That is the way I use var. For variables that are initialized with new statement I use var for others whose type is not as clear I use the actual type. – Thedric Walker Apr 10 '09 at 16:50
  • I realize this is an old question. However I am wondering in this example if using `var` is ideal, compared to declaring using an Interface? If you use var, anything can be assigned, while with an Interface you ensure the refactor adheres to what is expected. Isn't using `var` dangerous in this respect? – navigator_ Oct 28 '14 at 18:45
  • @navigator_ I missed the original comment, but if you change something that breaks the code, var is still strongly typed and it's still a compile-time error that you fix before anyone ever sees the problem. If you change a method so it returns something that doesn't work, the compiler still catches this. – Joel Coehoorn Jun 09 '16 at 03:27
20

You don't need to have the type in the line to make it more readable, its a matter of personal preference. I do like the var variation:

var currentTab = tabCaseNotes.TabPages[e.Index];
var itemRect = tabCaseNotes.GetTabRect(e.Index);
var fillBrush = new SolidBrush(Color.Linen);
var textBrush = new SolidBrush(Color.Black);
var sf = new StringFormat
   {
      Alignment = StringAlignment.Center,
      LineAlignment = StringAlignment.Center
   };

Update: I will add a controversial view on it. Unless I am reading code from a book, I don't usually care what's the specific type for understanding some lines of code I am reading. Consider the .GetTableRectangle(e.Index), for which you are not showing the code that operates on it:

var itemRect = tabCaseNotes.GetTableRectangle(e.Index);
//do some operations on itemRect

While reading that specific code I will get more to understand it from the operations on itemRect than from its type. It can be IRectangle, Rectangle, CustomRectangle, and still won't say much on what the code is doing with it. Instead I care more for the itemRect.Height, itemRect.Width or itemRect.GetArea() along with the logic involved.

Update 2: As others have pointed out you can turn it off. Make sure to keep the team with the same practices, or you will probably end up with making changes one way or the other each time a different person touches the code. See: http://www.jetbrains.com/resharper/features/codeTemplate.html

eglasius
  • 34,909
  • 4
  • 58
  • 105
  • I have been using var for some time now and couldn't go back. When I work on a legacy project with Resharper I find it hard to stop myself doing a global replace.. I've never had a bug that was caused by using var. These days all the bugs are in the client side code. It's never the C#. Using var has made no difference to the occurrence of bugs in my experience. – Norbert Norbertson Jul 21 '17 at 10:11
15

Resharper doesn't want you to use var, it is giving you the option. If you do use var it will then give you the option to use an explicit type, so you can't win:-).

EDIT - interesting link discussing the topic.

It seems it can be turned off, go to Resharper -> Options -> Code Inspection -> Inspection Severity and scroll down a little to see the options related to var.

Steve
  • 8,301
  • 1
  • 24
  • 37
  • 4
    I often use this to my advantage. That is, if I'm not 100% sure what a a method is returning, I use `var` and then use a keyboard shortcut to make ReSharper convert `var` to the explicit type. – Axel Örn Sigurðsson Aug 21 '13 at 11:11
7

Resharper thinks it is best-practice, but some people disagree as you have read in the linked post. I like to use explicit declaration for increased readability, but to each their own. If you want to use explicit declaration, you can disable the rule in Resharper.

Mark Sherretta
  • 9,930
  • 4
  • 35
  • 42
7

In C#, I prefer to use var everywhere. Why? For the same reason that I use firstName instead of strFirstName or amount rather than intAmount. Sure, the more verbose way is more readable on a piece of paper or—as you pointed out—a book, but none of my code has shown up in a book yet.

Now, I asked a co-worker of mine a while back about this intAmount business and he brought up a very good point. He said that it's useful in a straight-up text editor, but when you have Intellisense, you can get the same information and more by just hovering over the variable.

Lastly, although I appreciate the happy medium that others have pointed out (i.e. using var with the new statement) and the argument is valid and strong, I'm inclined to steer away from that on the sole basis of consistency and short-hand readability. My consistency argument is that if readability is so important to you, then why don't you also use intAmount so you can tell the data type later on in the code?

jedmao
  • 9,166
  • 9
  • 51
  • 63
  • 6
    Looking at the post it is clear why your code never gonna make it into a book. A method should not be so long that intAmount is needed (Coding Practices), but if you use `var xyz = Silo.GetWeight()` you will never know if weight is double, int, float or something more obscure, maybe a struct with weight and a unit? Then later you try to do a code review and will notice that rounding can matter a lot. – Offler Jun 24 '13 at 12:58
  • 1
    Um, who says I would write `var xyz = Silo.GetWeight()`? I would never write that. I would, however, write `var weight = Silo.GetWeight()` and I would know exactly the data type when I hover over the variable in Visual Studio. We have excellent tools today, so there's no reason to use Hungarian notation. – jedmao Jun 25 '13 at 15:58
  • 5
    Hovering costs time. Code reviews in larger companies are mostly not done in visual studio (for example: i know a lot of medical solutions where the complete VS part is not used in reviews. Sometimes a beamer is used, mostly an own program (also the builds are completly independent of VS, because there you can use settings which aare different for each programmer, the build system use an own make with fixed parameters - VS is only used as editor) directly reading 10 lines of coede is faster then read, hover, focus and so on. Try to do service on legacy systems. More readable = benefit on time – Offler Jun 26 '13 at 06:19
  • 2
    Lets make an example. `var weight = Tumor.GetWeight(); var volume = Tumor.GetActualVolume(); if(volume != 0) var density = weight / volume; // do some long running stuff with density` Do you notice quickly what can make problems? In a code review where you only see the code? If volume is a double in most cases it is likely that you will have roundings and comparing to an int or to 0.0 / 0d makes no sense. This information is missing, you new to hover. Think about: `class Tumor{... public double? GetDensity(){...}}` What if the var is put to a DB (Even tried to repair NaN in DB?} Getting – Offler Jun 26 '13 at 07:04
  • 7
    worse if somebody refactors code. In your review `weight` and `volume` are flows. Somebody refactors weight/volume to descrete values, e.g. int. Guess what: Not always all users of a method are known. So it won't break something if you use var. Some find it cool: `refactoring is easier`. Others will notice that you don't need to treat a tumor with a zero density, and that this can be with pos values, e.g. a weight of 1 and a volume of 2. No compiler warning, no impact? In such cases using `var` is really dangerous. For a long time nobody will notice the change. And this is only a short example – Offler Jun 26 '13 at 07:06
  • 1
    It's a strong argument, Offler. Touché. – jedmao Jun 27 '13 at 07:14
  • 2
    @Offler If you're worried about code like that, write better-designed code. What your code appears to be actually asking is _if the tumour has a volume, calculate the density_, or actually _if the tumour has a density do something_ So, write that code, rather than overload the meanings. `if (Tumor.HasDensity) { var density = Tumor.GetDensity() // do long-running stuff }` Now you have pushed those pesky number-type specific calculations into the class where they can be much more easily controlled for correctness. In general, these kind of problems can be avoided by better design. – nicodemus13 Feb 03 '15 at 22:47
  • 1
    @nicodemus13 that does not solve the problem. Lets say you have a density class and tumor.HasDensity will call the class. Same problem as above. Lets say its a third party app you can't change and it is refactored in such a way. I know at least one large medical company where you can't change dll's from other business units - they are just blind boxes. And you will try a var for such a something which can work or not? – Offler Feb 10 '15 at 13:09
0

This question is a really good way to start a flame war. However, you should do whatever you and whoever you're working with think is most readable. There are good arguments for both sides of the debate about var.

That said, if you think it's more readable to explicitly declare the type, that's your business. You don't have to do everything Resharper tells you to. You can even disable that rule if you want to.

dustyburwell
  • 5,605
  • 1
  • 24
  • 34
  • some people care about every little detail... coders are often MBTI-INTJ, and that often means being anal-retentive and / or picky. Regretfully I'm often both. – Hardryv Dec 15 '09 at 19:03
0

You can indeed turn it off, and I have. I'll admit that it's nice in some cases where the class type name is long, like:

SuperDisconfibulator sd=new SuperDisconfibulator();

would be a good candidate for being shortened to var, but personally that's the only time that I would want it to change. I don't think its a good idea to use it when a variable is being assigned from the return value of a method (like in your second line), because it might not be immediately clear what exactly the variable type it is it returns.

ryeguy
  • 60,742
  • 51
  • 186
  • 256
  • I actually prefer verbose variable naming, that way even if I didn't write it I likely have at least an idea what the original developer was up to. – Hardryv Dec 15 '09 at 18:58