Take the 2-minute tour ×

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#.

Thanks for sharing.

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

6 Answers

up vote 39 down vote accepted

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.

share|improve this answer
I also use 'var' in foreach statements where I only care about enumerating a collection, not necessarily about the type of each item. –  Anna Lear Feb 2 '11 at 18:32
And as Jesse pointed out anonymous types ;) –  Mike Brown Feb 2 '11 at 18:43
@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. –  Thanos Papathanasiou Nov 9 '11 at 18:47
@ThanosPapathanasiou Sure, yeah. Same thing goes for the Controls collection in Windows Forms and probably other situations, too. –  Anna Lear Nov 9 '11 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 Mar 7 '13 at 16:49
add comment

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.

share|improve this answer
forgot all about anonymous types! –  Mike Brown Feb 2 '11 at 18:41
At my last job I was told I'd be fired if i kept using the "var" keyword... –  hanzolo Sep 18 '13 at 19:44
That's extreme, but your company's initiative. Glad it's your "last" job, though! :) –  Jesse C. Slicer Sep 18 '13 at 20:11
add comment

From MSDN:


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;


var myFloat=100;


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


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.

share|improve this answer
add comment

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)

    // 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);
share|improve this answer
add comment

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.

share|improve this answer
add comment

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

share|improve this answer
add comment

Your Answer


