35

In C#, am I encouraged to use the all-purpose var keyword for every variable declaration? If yes, do I have to mention those special characters for literal values within the variable declaration like the M for decimal in the following statement:

var myDecimal = 14.5M;

If it makes a difference, I'm trying to do some web development with C#.

5
  • 7
    Has a dozen dupes over at SO (where it belongs IMHO).
    – user7043
    Commented Feb 2, 2011 at 18:15
  • 1
    The same questions are coming to C++ with C++0x repurposing auto. Commented Feb 2, 2011 at 18:39
  • 5
    Eric Lippert of the C# compiler team recently blogged about this: blogs.msdn.com/b/ericlippert/archive/2011/04/20/… Commented Apr 22, 2011 at 16:13
  • There are six billion dupes of this question.
    – DeadMG
    Commented Nov 10, 2011 at 5:29
  • @DeadMG that makes'em six billion and one.
    – wassimans
    Commented Nov 12, 2011 at 18:50

6 Answers 6

54

There has been a lot of dispute over the use of var. My general rules are the following.

  • When the type is obvious such as when the right hand of the assignment is a constructor, use var.
  • When the type is complex to write, such as a LINQ query (the reason for var in the first place) use var.
  • For ambivalent types (your Decimal being an example) where you want to make sure that your variable is correctly typed, spell it out.
  • Anonymous types have to use var.
  • In all other cases spell out the type.

Basically, the goal is to make it easier to read the code. If you feel that var suffices because the assignment is obvious, use var. Use the full type name as a hint for the reader when you feel it's necessary.

5
  • 9
    I also use 'var' in foreach statements where I only care about enumerating a collection, not necessarily about the type of each item.
    – Adam Lear
    Commented Feb 2, 2011 at 18:32
  • 1
    And as Jesse pointed out anonymous types ;) Commented Feb 2, 2011 at 18:43
  • 4
    @AnnaLear sometimes you have to care though. foreach (var row in datatable.Rows) in this case var is an object not a DataRow as one would expect. Commented Nov 9, 2011 at 18:47
  • @ThanosPapathanasiou Sure, yeah. Same thing goes for the Controls collection in Windows Forms and probably other situations, too.
    – Adam Lear
    Commented Nov 9, 2011 at 18:51
  • I usually use var except when i want to be sure of the type of my variable (like when i want to be sure that the value is double for example)
    – eka808
    Commented Mar 7, 2013 at 16:49
14

When to use var is a programming "holy war". There is precisely one place where it's required: when the result of an operation creates an anonymous type, such as:

var result = new { Name = "John", Age = 35 };

Anywhere else, it's optional and really up to your coding standard to use it or not in the other situations.

And yes, you will need the special characters for literals to let the compiler know what it is on the right-hand side. In your example, without the M, the default is double rather than decimal.

3
  • 1
    forgot all about anonymous types! Commented Feb 2, 2011 at 18:41
  • At my last job I was told I'd be fired if i kept using the "var" keyword...
    – hanzolo
    Commented Sep 18, 2013 at 19:44
  • That's extreme, but your company's initiative. Glad it's your "last" job, though! :) Commented Sep 18, 2013 at 20:11
7

From MSDN:

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.

I really, really don't like implicit typing. On the surface it tends to make code more readable, but can lead to lots of problems down the road. If a dev changes a variable initializer, say, from

var myFloat=100f;

to

var myFloat=100;

or

var myFloat=100.0;

The type will change, resulting in whole slew of compiler errors or, if it's in a web view and you're not using the post-build step to precompile your views, a whole slew of runtime errors that won't be caught without effective pre-deployment testing.

Implicit typing also doesn't work everywhere (from the same MSDN link)

var can only be used when a local variable is declared and initialized in the same statement; the variable cannot be initialized to null, or to a method group or an anonymous function.

var cannot be used on fields at class scope.

Variables declared by using var cannot be used in the initialization expression. In other words, this expression is legal: int i = (i = 20); but this expression produces a compile-time error: var i = (i = 20);

Multiple implicitly-typed variables cannot be initialized in the same statement.

If a type named var is in scope, then the var keyword will resolve to that type name and will not be treated as part of an implicitly typed local variable declaration.

Keeping your code consistent (in this case, using explicit typing everywhere) is a very, very good thing. In my opinion, var is lazy and provides no real benefit, and introduces yet another potential point of failure in an already complex process.

2017 Update

I completely changed my mind. When working in C#, I use var most of the time (excepting things like interface-type variables and such). It keeps the code terse which improves readability. Still, though - pay attention to what the resolved type really is.

3
  • Wondering what changed your mind, @3Dave. I still 100% agree with your original point: "var is lazy and provides no real benefit, and introduces yet another potential point of failure in an already complex process".
    – Dan
    Commented Feb 14, 2019 at 17:38
  • @Dan It really came down to readability. A competent developer can pretty quickly determine what's on the initialization side of a declaration without issue. Just like not using this. everywhere, or saying System.Blah.SomeType instead of a using, which I still find incredibly annoying, more terse code is - at least for me - typically easier to visually parse. There are still many scenarios where explicit typing is the right choice. But, these days I'm less of a language lawyer than someone just trying to get clean code out the door.
    – 3Dave
    Commented Feb 14, 2019 at 19:37
  • @Dan (Of course, I'm also the guy that uses using namespace std; in .cpp files. (Not headers, as I'd prefer to avoid being tarred and feathered.)
    – 3Dave
    Commented Feb 14, 2019 at 19:38
3

The C# Reference shows the following to illustrate good vs bad use of this construct:

The following example shows two query expressions. In the first expression, the use of var is permitted but is not required, because the type of the query result can be stated explicitly as an IEnumerable. However, in the second expression, var must be used because the result is a collection of anonymous types, and the name of that type is not accessible except to the compiler itself. Note that in Example #2, the foreach iteration variable item must also be implicitly typed.

 // Example #1: var is optional because 
    // the select clause specifies a string 
    string[] words = { "apple", "strawberry", "grape", "peach", "banana" };
    var wordQuery = from word in words
                    where word[0] == 'g'
                    select word;

    // Because each element in the sequence is a string,  
    // not an anonymous type, var is optional here also. 
    foreach (string s in wordQuery)
    {
        Console.WriteLine(s);
    }

    // Example #2: var is required because 
    // the select clause specifies an anonymous type 
    var custQuery = from cust in customers
                    where cust.City == "Phoenix" 
                    select new { cust.Name, cust.Phone };

    // var must be used because each item  
    // in the sequence is an anonymous type 
    foreach (var item in custQuery)
    {
        Console.WriteLine("Name={0}, Phone={1}", item.Name, item.Phone);
    }
0

The var keyword only requests the compiler to deduce the type of the var type variable automatically. Hence, if you want to store a decimal type variable in a var variable, you need to use the m. Likewise if you are storing a string you need to enclose it in quotes.

0

For me I don't use var for the following cases :

  • When I want to be sure of the type of my variable (for example to be sure that the type used is double and not decimal, and this is a big deal trust me !)
  • Polymorphic code like Fruit foo = new Apple();. In this case, I think var is to avoid and using the parent class (here Fruit) is better by allowing a better understanding of the code logic and limitation of the probable bugs (With var, no check of the polymorphic concept !)

For the rest, I think it depend of the case and of the background of the developer. Some people from the PHP world will prefer not taking care of the variable types, and some people from the Java world will just think var is an heresy and the more verbose it is the better it is.

You will have to make your personal opinion :)

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