Search
Winners

Win Prizes

Social Presence
Twitter Twitter LinkedIn YouTube Google

Like us on Facebook
Advertisements
Top Articles Author
Thu, 21-Aug-2014 Authors
All Time Authors
Sourav.Kayal
39750
Sheonarayan
37300
Niladri.Biswas
33350

Latest members | More ...


(Statistics delayed by 5 minutes)
Ads
 Article

What is the use of "VAR" keyword in c#?

Questpond
Posted by under C# category on for Advance level | Points: 250 | Views : 47033 red flag
If you found plagiarised (copied) or inappropriate content,
please let us know the original source along with your correct email id (to communicate) for further action.
Rating: 5 out of 5
1 vote(s)
Var keyword is an implicit way of defining DataTypes. Implicit means indirect way of defining variable types.

What is the use of “VAR” keyword in C#?

If you are feeling too hectic to read the complete article, you can click on the below video and watch the whole demonstration of the article.


“Var” Keyword = Var keyword is an implicit way of defining DataTypes. Implicit means indirect way of defining variable types.

In simple words by looking the data at the right hands side the left hands side data types is defined by the compiler during the generation of the “IL” code.

Let me show a simple example what does implicit (indirect) way of defining DataTypes means.



In the above diagram you can clearly see that the variable “i” has directly define with the data type as “int” which is called as Explicit way of defining.

Now, let’s see how we can define data types in implicit (indirect) way.



In the above diagram you clearly see that how exactly you can declare variables using “Var” keyword which is also called as Implicit way of defining.

Note: - “Var” keyword defines data type statically and not on runtime.

Let me prove the above point with some practical demonstration so that you can get a better idea.
To see simple demonstration create a new console application for that just Go To > File > New > Project > Windows > Console Application.



Now just create a variable using “Var” keyword like below code snippet.

class Program
{
static void Main(string[] args)
{
var i = 123;
}
}

In the above code snippet I have declared a variable “i” using Var keyword and also assign value to it as “123” which means that the variable “i” will have data type as “int” as we have discussed earlier above.

Now, let’s try to add value as string to the variable “i” and try to compile the code and see that what the compiler has to say about it.

class Program
{
static void Main(string[] args)
{
var i = 123;
i = "Feroz";
}
}


In the above code snippet you can see that I have tried to add string value to the “i” variable and try to compile the code, the compiler throws an error like below diagram.



The above error diagram shows that cannot implicitly convert type ‘string’ to ‘int’ as the variable “i” is declared as “int” data type.

Let me prove the above point in one more way so that there is no confusion in your mind regarding the data type assigned to the variable “i” according to the value defined.

Just follow the below diagrams.

Open Visual Studio Command Prompt and type “ildasm” and press enter a new window will open from that click on file > open and just browse to your application select the application name and click open.




Now, let’s see what’s the use of “Var” keyword an in what scenario it is helpful.

The “Var” keyword provides two important uses as follows.

1. When you have long class names and your code is not readable so by using “Var” keyword the code becomes short and sweet.

2. When you are using LINQ and anonymous types “Var” keyword reduces your code for creating special classes.

Let also prove the above points one by one.

1. When you have long class names and your code is not readable so by using “Var” keyword the code becomes short and sweet.

class clsSomeBigClassToDoSomething<T, T>
{
public string CustomerCode;
}
class Program
{
static void Main(string[] args)
{
//lets create an instance of the above class
clsSomeBigClassToDoSomething<string, string> obj = 
new clsSomeBigClassToDoSomething<string, string>();
}
}

In the above code snippet you can see that the class name is too big and is not also easily readable. Now let’s see how “Var” keyword helps us from this situation and make this code more readable and understandable.

static void Main(string[] args)
{
//lets create an instance of the above class
// now the code has become sweet and sort
var obj = new clsSomeBigClassToDoSomething<string, string>();
}

Now you can see that how “Var” keyword make your code short and sweet and also made “obj” object strongly type as you can see in below diagram.



In above diagram you can see that the “Var” keyword not only shorten the code but also make the “obj” object strongly type.

Now, let also prove the second point.

2. When you are using LINQ and anonymous types “Var” keyword reduces your code for creating special classes.
Let see how “Var” keyword is usefull with LINQ and Anonymous type let go and create an array of strings and fill this array with static data.

class MyData
{
public int Len;
public string Value;
}
class Program
{
static void Main(string[] args)
{
//use of var keyword with LINQ and Anonymous type.
//creating array 
string[] Arr = { "Feroz", "Kalim", "Shaam", "Moosa" };
//return values which are greater than length 5.
IEnumerable<MyData> obj = from x in Arr where x.Length >
 5 select new MyData { Len = x.Length, Value = x };
}
}


In the above code snippet you can see that I have to create an extra class in order to create variables, so that the length is assigned to the Len variable and data is assigned to the Value variable.

Now, let’s see how “Var” keyword helps us to get rid of the extra class creating and also no need to create separate variables to assign the length and data.

class Program
{
static void Main(string[] args)
{
//use of var keyword with LINQ and Anonymous type.
//creating array 
string[] Arr = { "Feroz", "Kalim", "Shaam", "Moosa" };
//return values which are greater than length 5.
var obj = from x in Arr where x.Length > 5 select new { Len = x.Length, Value = x };
}
}

In above code snippet you can clearly see that I have not created an extra class with variables like Len and Value and also when you will browse to the data you will find that object is now being created as strongly typed like below diagram.



Do not forget to see our .NET interview question videos by clicking on .NET interview questions

Page copy protected against web site content infringement by Copyscape
About the Author

Questpond

Full Name: Shivprasad Koirala
Member Level:
Member Status: PanelMember,Member,Microsoft_MVP,MVP,Administrator
Member Since: 9/3/2008 2:16:27 AM
Country: India
www.questpond.com
http://www.questpond.com

I am a Microsoft MVP for ASP/ASP.NET and currently a CEO of a small
E-learning company in India. We are very much active in making training videos ,
writing books and corporate trainings. Do visit my site for 
.NET, C# , design pattern , WCF , Silverlight
, LINQ , ASP.NET , ADO.NET , Sharepoint , UML , SQL Server  training 
and Interview questions and answers

Login to vote for this post.
Found interesting? Add this to:


Comments or Responses

Posted by: Akiii on: 9/5/2011 | Points: 25

Excellent article sir....

Thanks and Regards
Akiii

Posted by: Vuyiswamb on: 9/6/2011 | Points: 25

nice article

Posted by: Hareesh on: 3/26/2012 | Points: 25

Great article sir

Thanks®ards
hareesh

Login to post response

Comment using Facebook(Author doesn't get notification)