Understand VAR Keyword in C# 3.0 using examples

One my friend Robin Gangawane from "Goregaon - Mumbai", who is currently working in a small software firm and a newbie in .net technology, via email has suggested me a very good question i.e. "what is a use of VAR keyword and illustrate difference between dynamic keyword and VAR keyword using an example" and asked me to write an article on the same. I'm very grateful to Mr. "Robin Gangawane" for following onlinebuff tutorial post. Like Mr. Robin Gangawane if you have any doubt/query or want to suggest me a "Question - Frequently Asked in an Interviews" then feel free to drop a question via email or comment.

Explain VAR Keyword in C# 3.0?

Before we talk more about "VAR" keyword. Let me make it clear that this "VAR" keyword is not similar to the "var" keyword used in javascript or "Variant" data-type used in Visual Basics.

VAR keyword is an implicitly way of (indirect) defining a data-type. "VAR" keyword is a static type means it is an implicitly way of declaring strong type.

All variables declared as "VAR" are strongly typed or statically typed.

Syntax of VAR keyword

var x = 9;

So as you see from above code to define a VAR keyword variable is pretty simple just you need to define "var" followed by “variable-name“.

So now you must be thinking what type of data-type is this "VAR" keyword and how it become the strong type.Let me show you using an example.

VAR is a Static Type - Let's Prove It

Let's define two variables one with "var" keyword and another one with an "int" keyword.

class Program {

	public static void Main()
	{
		var x = 9;
		int x = 9;
	}

}

So my friend, "VAR" type is not the actual type. The actual type is decided by the compiler during compile-time depending on the right-hand side value.

When you define a VAR type variable with attached data to it. The moment you attach the data to a VAR keyword variable, the compiler will automatically detect right hand side value and depending on data compiler decides the actual type and turns that VAR keyword variable to strong type variable of a same type. On right hand-side if you define "interger" number then compiler will convert var-type variable to "int" type or if you define "string" then compiler will convert var-type variable to "string" type or if you define "floating number" then compiler will convert var-type variable to "double" type.

So in a way above both above lines are same, if you declare "var" or "int" with data "9" for a compiler is one and the same means both variables will inherit from a same common base class called System.Int32.

Only one difference in both lines i.e.

int x = 9;

Above line is explicit declaration of "integer variable" with a common base class System.Int32.

var x = 9;

Above line is implicit declaration of "integer variable" with a common base class System.Int32.

Proof using ILDASM tool

class Program{

public static void Main(string args[]){

   var x = 9;

}

}

Now, We will compile this above program or build this above program (short cut press CTRL + F5).

When we build this program visual studio will generate exe file of this program.

Now, let's open up visual studio command prompt (you can find visual studio command prompt in program files -> visual studio folder 2010 -> Visual Studio Tools -> Click on the visual studio command tool.

After opening of visual studio command prompt type the following code that is "ILDASM" to open ILDASM tool.

In "ILDASM" tool open the exe file (you can find the exe file in the Bin folder). After you open up the exe file as shown in below image.

Click on the Main() method, See in the above it is been highlighted in a blue color. Double click on the Main() method to see the IL code of the exe.

As you see from above example using an "ILDASM tool" it is showing that VAR keyword variable "x" is inherited from System.Int32 class.

Let's do one more example using string data.

class Program{

	public static void Main(string args[]){

	var x = "Khadak Bist";

	}

}

As you see from above example using an "ILDASM tool" it is showing that VAR keyword variable "x" with value "Khadak Bist" is inherited from System.String class.

So friends..! By seeing above examples it is been proved that during compile-time depending on right-hand side value, "VAR" keyword changes its type to that actual type and becomes strong-type.

Let's do one more example using class-name.

public class clsTestVar{


     private string _bookname = "";
     private int _bookno = 0;

     public string BookName{
       
        set{
          _bookname = value;
        }
	get{
           return _bookname;
        }

     }

     public int BookNo{
       
        set{
          _bookno = value;
        }
	get{
           return _bookno;
        }

     }
}

class Program{

	public static void Main(){

	var x = new clsTestVar();
	
	x.

	}

}

Now use that "x" variable and click on the DOT (.) operator. The moment you click on the DOT(.) operator visual studio intellisense will throw all the properties of the class "clsTestVar". It means during compile-tile only it has got converted to the actual-type.

Conclusion : Hence it is been proved that "VAR" type is not a actual-type. The actual-type is been decided by the compiler during compile-time depending the right-hand side value and further it converts that actual-type to same-type and makes strong-type.

Use of VAR keyword using example

The use of "VAR" keyword is very important in a program because it increases code readability and code simplicity. It is sometime optional to use "VAR" keyword with primitive data-types like int, string, double etc but it is sometimes required to use to improve code readability.

So use of "VAR" keyword with primitive data-types it completely optional and it is upto individual programmer wheather he/she wants to use it or not.

Most of the experienced programmers/developers feels that direct way of defining (Explicit Defining) a data-type is much simpler and cleaner as compared to indirect way of defining (Implicit Defining) a data-type. So for simple or primitive data-types "VAR" keyword will cause more confusion and will create more complexity to understand.

Let me show you the actual use of "VAR" keyword in a program.

Use of "VAR" keyword with LINQ and Anonymous Types

"VAR" keyword is very useful in dealing with anonymous types. .NET experts also suggest to use "VAR" keyword with LINQ and anonymous types. In c-sharp it is easy to define an Anonymous types by using "new" keyword of C#. "new" keyword allows to create new types without defining them. Here is the example of it:

   class Program
    {
        static void Main(string[] args)
        {
            var x = new {ID = 1, Name = "Robin Borde" };

            Console.WriteLine("Display Output : {0} ID is {1} ",x.Name, x.ID);
         
        }
    }

As you see from above code, Using "VAR" we have made the code much simpler and more readable to understand. So it is best practices to use "VAR" keyword with an anonymous types.

Display Output

Display Output : Robin Borde ID is 1;

LINQ Query with an anonymous type

DotNet experts also recommend to use of "VAR" keyword with LINQ Query (Language Integrated Query in .NET) because it makes the code more readable, simplicity with strong type and using "VAR" keyword we can easily able to access the anonymous types.

Anonymous Type with an object.

    class Program
    {
        static void Main(string[] args)
        {
            string[] arrFruits = new string[] {"apple", "mango", "grapes", "banana", "orange", "watermelon"};

            object x = from a in arrFruits where a.Length > 5 select new {a.Length, a};

            foreach (object c in x)
            {
                Console.WriteLine(c.
            }
          
        }
    }

If you see the above source code we cannot able to see the anonymous types using an object. Now lets replace an object with a "var" type.


 class Program
    {
        static void Main(string[] args)
        {
            string[] arrFruits = new string[] {"apple", "mango", "grapes", "banana", "orange", "watermelon"};

            var x = from a in arrFruits where a.Length > 5 select new { FruitName = a, Len = a.Length };

            foreach (var fruits in x)
            {
                Console.WriteLine("{0} with length {1}", fruits.FruitName,fruits.Len);
            }
         
        }
    }

As you see in our above code that we have used string array "arrFruits" in a LINQ query with an anonymous type to iterate an array whose value length is greater than 5. After iterating an array using LINQ and anonymous we have displayed the anonymous type values using "FOR-EACH" loop.

Display Output

Use of "VAR" keyword with long class names


    public class clsTestVaroftheConsoleApplications
    {
        private string _bookname = "";
        public string BookName
        {
            set
            {
                _bookname = value;
            }
            get
            {
                return _bookname;
            }

        }
       
    }

It is optional again it depends on the programmer wheather he/she wants to follow this approach. "VAR" keyword simplifies writing of long class names. An example is shown below.

public class clsTestVaroftheConsoleApplications
{
///code goes here
}

static void Main(string[] args)
{
  
   //Regular Approach 
   
   clsTestVaroftheConsoleApplications obj = new clsTestVaroftheConsoleApplications();

   //Var Approach
   var obj = new clsTestVaroftheConsoleApplications();
    
  
}

Difference between VAR keyword and Dynamic keyword

VAR Keyword is static type or strong type.

Dynamic keyword is also static type.

VAR : The actual type is decided on compile-time.

Dynamic : The actual type is decided on run-time.

VAR : Error-checking is done on compile-time.

Dynamic : Error-checking is done on run-time.

VAR : Early bounded type.

Dynamic : Late bounded type.

 

class Program{

   dynamic str = "Shiv";
}

class Program{

   var str = "Shiv";
}

So as you see friends this is all about C# 3.0 "VAR" keyword. If you have any doubts or any suggestion or want to drop a question then feel free to post via comment section box. Find comment section below this article. Thank You..!

If you like this article kindly share it with your friends on FB, Twitter and Google+.

Author: Gurunatha Dogi

Gurunatha Dogi

Gurunatha Dogi is a software engineer by profession and founder of Onlinebuff.com, Onlinebuff is a tech blog which covers topics on .NET Fundamentals, Csharp, Asp.Net, PHP, MYSQL, SQL Server and lots more..... read more

Comments

64x64
By Priya on 2015-05-29
if we use explicit variable, it is more simpler and readable so why am use this var? without benefits of linq and anonymous type

Add a Comment