Congratulations to all monthly winners of May 2013 !!! They have won INR 2900 cash and INR 27497 worth prize.
Go to DotNetFunda.com
Twitter TwitterLinkedIn
YouTubeGoogle
 Online : 18544 |  Welcome, Guest!   Register  Login
Home > Articles > C# > What is the use of "VAR" keyword in c#?

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

1 vote(s)
Rating: 5 out of 5
Article posted by Questpond on 9/5/2011 | Views: 14513 | Category: C# | Level: Advance | Points: 250 red flag

Advertisements

Advertisements
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

Advertisements

If you like this article, subscribe to our RSS Feed. You can also subscribe via email to our Interview Questions, Codes and Forums section.

Page copy protected against web site content infringement by Copyscape
Found interesting? Add this to:



Please Sign In to vote for this post.

Experience:0 year(s)
Home page:http://www.questpond.com
Member since:Wednesday, September 03, 2008
Level:Starter
Status: [PanelMember] [Member] [Microsoft_MVP] [MVP] [Administrator]
Biography:

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

 Responses
Posted by: Akiii | Posted on: 05 Sep 2011 10:58:18 AM | Points: 25

Excellent article sir....

Thanks and Regards
Akiii

Posted by: Vuyiswamb | Posted on: 06 Sep 2011 02:29:45 AM | Points: 25

nice article

Posted by: Hareesh | Posted on: 26 Mar 2012 03:29:23 AM | Points: 25

Great article sir

Thanks®ards
hareesh

>> Write Response - Respond to this post and get points
Related Posts

This article demonstrates how to implement queue in C# with the help of easy examples. Queue is a data structure element where elements are in form FIFO.

In this quick post we will learn all about destructors and its all properties.

Hi guys... Given below is the complete working code to call REST based web service using OAuth 1.0 authorization with RSA-SHA1 cryptography. The code actually contains 2 class file. Both these classes are given below. simply copy paste this in your solution and make neccessery changes as per your convenience and you are good to go.

We will continue with the same problem of the Customer Sales application discussed in Part I. We saw in the previous article, tangling code originated from cross cut concerns. We also found that to solve this problem we separate the cross cut concerns from main concerns.

Parallel programming is introduced in C# 4.0 using the Task libraries. There are many aspects of Parallel programming and how to use the Task libraries. Here, we will look into the Task from a beginner stand point. In this article, we will discuss about how to create an asynchronous method using Task.

More ...
About Us | Contact Us | The Team | Advertise | Software Development | Write for us | Testimonials | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you find plagiarised (copied) contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
Copyright © DotNetFunda.Com. All Rights Reserved. Copying or mimicking the site design and layout is prohibited. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks. | 6/19/2013 1:06:59 AM