Community Pick: Many members of our community have endorsed this article.
Editor's Choice: This article has been selected by our editors as an exceptional contribution.

The var keyword

JarrodDeveloper of Stuff
Published:
Updated:
Introduction
                                               
Was the var keyword really only brought out to shorten your syntax? Or have the VB language guys got their way in C#? What type of variable is it? All will be revealed.
 
Also called: Implicitly typed local variables
 
The var keyword – in VB
 
I have heard many an argument about this new addition to the C# language. One of the main debates being: It’s so VB like, It reminds me of Dim.  So this is all I am going to say about its use in VB (and only because I think if VB programmers use it may make their code just a little better).
 
Its use in VB is slightly different to that in C#.  This is because VB has always had an unknown type keyword (dim), so you have to explicitly “turn on” the functionality by using the “Option Infer On” at the top of your module.  So to finish off for VB: To use this functionality turn it on and the declare your Variable like so:
 
   Dim MyStringVariable = "hello world"
 
When hovering the mouse over MyStringVariable you will notice the tooltip text says Dim MyStringVariable As String.  So you will not be able to do your usual VB thing and change its type later on to an int!
 
The var keyword
 
First of all to ease all your minds the var keyword is not evil VB code creeping into your C# IDE!  It is strongly typed (which means that you cannot put a string into it and then later on change its type to an int).
 
It must not be confused with the object data type – it is also not an object.  So what is it?  It is whatever you want it to be when declaring the variable.  So if you type:
 
string MyString = "Hello world"; 
                      Console.WriteLine(MyString);

Open in new window

 
It is no different from typing
 
var MyString = "Hello world"; 
                      Console.WriteLine(MyString);

Open in new window

 
In fact, when you compile it the IL Code will look like this for both scenarios.
.method private hidebysig static void Main(string[] args) cil managed
                      {
                          .entrypoint
                          .maxstack 1
                          .locals init (
                              [0] string MyString)
                          L_0000: nop 
                          L_0001: ldstr "Hello world"
                          L_0006: stloc.0 
                          L_0007: ldloc.0 
                          L_0008: call void [mscorlib]System.Console::WriteLine(string)
                          L_000d: nop 
                          L_000e: ret 
                      }

Open in new window



 So what is the point - Is all this effort really to save me from typing out the extra three chars that there are in the word string?  Well yes, and no.  

First we will explore the Yes answer.  Since the addition of Generics in C# two  lines of code can become very long.  For instance:
 
Line1:  List<string> MyStringList = new List<string>();

Open in new window

Is shortened to

Line 2:  var MyStringList = new List<string>();

Open in new window


As you can imagine, some declarations can become quite long.

In line 1 you are saying:  I am declaring a List of strings and I want to assign it to a list of strings object.  Using the var keyword you are saying that I have a variable and it is a list of strings – you don’t have to say it twice.  To strengthen this point: You cannot declare a var and then initalise it later.  When using the var keyword you have to initalise it on the same line (Only exception is that you cannot initalise it using a collection initaliser).  And you cannot initalise it to a Lamda expression.
 
The following lines of code are errors and will not compile:
var x;

Open in new window

var x = null;

Open in new window

var x = {"1", "2"};

Open in new window

var x = () => { j = 10; return j > 9; };

Open in new window


Now we shall explore the No part of the answer.  

All this effort in not only to save me from typing out the extra three chars in the word "string."  There are actually types in C# that have no name.  These are called Anonymous types.  They are not any conventional type of object, but they do exist and you cannot initalise them without using the var keyword.
 
Example 1:
 
var Car = new { Manufacturer = "Audi", Model = "A4", Year = 2006, Colour = System.Drawing.Color.Blue };
                      Console.Write(Car.Colour + " " + Car.Manufacturer + " " + Car.Model + " " + Car.Year);

Open in new window



As you can see from the (pretty useless) example above that we now have an object which we don’t know what its name is, but we have assigned the variable Car to it, and Car has all of the valid properties to it. However it will print out to the console:
 
Color [Blue] Audi A4 2006
 
Example 2:
 
A more useful example would be when querying an Object / XML /  Anything using Linq.
 
var Articles = (from a in context.Articles
                                      orderby a.CreateDateTime descending 
                                      select  new { ArticalTitle = a.Title, Created= a.CreateDateTime }).Take(5);
                              
                      foreach (var article in Articles )
                      {
                           string s = article.ArticalTitle;
                           DateTime d = article.Created;
                      }

Open in new window



So instead of bringing back the SQL whole object (in this case) a new anonymous object is created and returned. This I suppose was the main reason for the keyword.
 
Conclusion
 
Using var should be embraced by developers worldwide. There is no way to misuse this keyword.  It is always good!  The only conceivable reason not to use it would be if you don’t know the data type of the “RHS” of the =. This could possibly lead to reading issues ... but not really.  Ie:
    var x = 0;  
you know 0 is an int.  Therefore x is an int.  However
    var c = MyObject.variable;
(a newbie to the project may not know what datatype variable is of class MyObject).  Developers working with the project should know.  Moreover, correctly named variables should sort out this issue.  Example: Without knowing anything about a class we could guess that the property StartDate is a type of System.DateTime.  Else whip the developer if it's a string!!!

Originally Posted @ http://www.zadeveloper.com/
7
7,959 Views
JarrodDeveloper of Stuff

Comments (15)

it_saigeDeveloper
CERTIFIED EXPERT
Distinguished Expert 2021

Commented:
@kaufmed,

Yes, that works for reference types but does not give you a *strict* value type; e.g. -
var x = (int)null; // Valid, but results in an int wrapped in a nullable; e.g. - Nullable<int> or int?

Open in new window

Which could just be splitting hairs but also why I prefer using the default keyword.

-saige-
CERTIFIED EXPERT
Most Valuable Expert 2011
Top Expert 2015

Commented:
A value type can never be null, so the point is moot. A nullable value type would work, though.

The "problem" with default--and mind you I really have no issue with default in general--is you have to know what the default value for the thing you are assigning is when you write it. The list isn't exhaustive, so it's not that big of a deal.
CERTIFIED EXPERT
Most Valuable Expert 2011
Top Expert 2015

Commented:
Also, your last example is not valid.
it_saigeDeveloper
CERTIFIED EXPERT
Distinguished Expert 2021

Commented:
Agreed on all points.

But in reality, do you have to *know* what the result of using default on a type is?  Can you just not check for type to default(type) equality [or inequality] by using:
SomeType == default(SomeType)

Open in new window

As you have attested, the list is not exhaustive and, for the most part, is intuitive.

Can I blame my last example on poor coffee intake?  ;)

-saige-
CERTIFIED EXPERT
Most Valuable Expert 2011
Top Expert 2015

Commented:
Contrived example, but:

int x = 10;
int y = default(int);

double z = x / y;

Open in new window


I agree, it's mostly intuitive:  number types are all zero, and reference types are null.

View More

Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.