<

The var keyword

Published on
17,290 Points
7,090 Views
7 Endorsements
Last Modified:
Awarded
Community Pick
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
Author:zadeveloper
Ask questions about what you read
If you have a question about something within an article, you can receive help directly from the article author. Experts Exchange article authors are available to answer questions and further the discussion.
Get 7 days free