Implicit Variable in C# 2008

C# 2008 allows for creating implicit variables using the ‘var’ keyword. But the usage of ‘var’ cannot be truly justified for just declaring a ‘int’ or ‘string’ in code as shown in example below.

var intNum = 5;

Console.WriteLine("intNum is a: {0}", intNum.GetType().Name);
Console.WriteLine("intNum is defined in: {0}", intNum.GetType().Namespace);

The output of the above program is

intNum is a: Int32
intNum is defined in: System

Here instead of using int in the declaration, we have used ‘var’ keyword. There is no difference between using ‘int’ or ‘var’ in the above example.
The real usage of ‘var’ comes in LINQ. Consider the following code.

int[] numbers = { 10, 20, 30, 40, 8, 7, 6, 2 };
var resultSet = from i in numbers where i < 10 select i;

foreach (var i in resultSet)
Console.Write("{0}", i);

Console.WriteLine("resultSet is a: {0}", resultSet.GetType().Name);
Console.WriteLine("resultSet is defined in: {0}", resultSet.GetType().Namespace);

Here resultSet is declared as a ‘var’. From the code, we understand that anytime, the resultSet will be an array of integers. But ‘resultSet.GetType().Name’ gives a surprising result.

resultSet is a: d__0`1
resultSet is defined in: System.Linq

So ‘var’ has its best usage in LINQ. So why use it in a normal program when the datatype can be used in itself.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s