Why should I use var instead of a type?

143,036

Solution 1

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

See also here for the performance question:

Solution 2

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

Solution 3

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

Solution 4

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.

Share:
143,036

Related videos on Youtube

IAdapter
Author by

IAdapter

Updated on January 02, 2020

Comments

  • IAdapter
    IAdapter over 4 years

    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?

    • Erik Funkenbusch
      Erik Funkenbusch over 13 years
    • Meydjer Luzzoli
      Meydjer Luzzoli over 13 years
      -1 : This has been covered so many times before, and the duplicates are easily found by searching the site.
    • IAdapter
      IAdapter over 13 years
      @Greg Beech I disagree, not everybody knows its a ReSharper's bug, I thought it means something, but I was wrong.
    • Erik Funkenbusch
      Erik Funkenbusch over 13 years
      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 resharper.blogspot.com/2008/03/…
    • IAdapter
      IAdapter over 13 years
      @Mystere Man funny link, they say "It removes code noise.", they do know a lot about make a useless noise.
    • NoWar
      NoWar about 10 years
    • Maverick Meerkat
      Maverick Meerkat almost 6 years
      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 docs.microsoft.com/en-us/dotnet/csharp/programming-guide/… 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.
    • devklick
      devklick about 5 years
      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<MyObject>, 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.
  • IAdapter
    IAdapter over 13 years
    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".
  • Peposh
    Peposh over 13 years
    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.
  • Jon Skeet
    Jon Skeet over 13 years
    @01: I wouldn't say a green light is a "warning". Orange or red, yes... but green?
  • IAdapter
    IAdapter over 13 years
    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
    IAdapter over 13 years
    but like many frameworks like this ReSharper is forcing his taste ;)
  • Jon Skeet
    Jon Skeet over 13 years
    @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.
  • Erik Funkenbusch
    Erik Funkenbusch over 13 years
    Resharper is not forcing anything. It's a suggestion. That's why it's green.
  • IAdapter
    IAdapter over 13 years
    @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.
  • Erik Funkenbusch
    Erik Funkenbusch over 13 years
    @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.
  • carny666
    carny666 about 10 years
    @Peposh yup.. same here that's why I stopped using it... until I started using ReSharper that is.
  • JonN
    JonN about 10 years
    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<string, KeyValuePair<string, int>> NestedKVP y1 = new NestedKVP("key", new KeyValuePAir<string, int>("subkey", 5)); `
  • El Mac
    El Mac about 8 years
    @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?
  • Jon Skeet
    Jon Skeet about 8 years
    @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.
  • user1040975
    user1040975 almost 8 years
    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.
  • Glurth
    Glurth almost 8 years
    " 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.
  • arbitrarystringofletters
    arbitrarystringofletters over 7 years
    @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!
  • Alan
    Alan over 6 years
    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.
  • Max Mustermann
    Max Mustermann about 6 years
    Only Codestyle? I don't agree: dotnetfiddle.net/FwpqlU
  • robbie70
    robbie70 almost 6 years
    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.
  • Alan
    Alan over 5 years
    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.
  • Ori Nachum
    Ori Nachum about 4 years
    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.
  • davehay
    davehay almost 4 years
    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.
  • ChiefTwoPencils
    ChiefTwoPencils over 2 years
    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.
  • Tom Lint
    Tom Lint almost 2 years
    @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