56

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.

0

7 Answers 7

46

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.

3
  • 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. Apr 10, 2009 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, 2014 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. Jun 9, 2016 at 3:27
22

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

1
  • 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. Jul 21, 2017 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.

1
  • 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. Aug 21, 2013 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.

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?

8
  • 7
    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, 2013 at 12: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, 2013 at 6: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, 2013 at 7: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, 2013 at 7:06
  • 4
    @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. Feb 3, 2015 at 22:47
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.

1
  • 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, 2009 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.

1
  • 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, 2009 at 18:58

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