Implicit Variable in C# 2008
Posted on by
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.
1 2 3 4 | 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
1 2 | 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.
1 2 3 4 5 6 7 8 9 10 | 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.
1 2 | 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.
Possibly Related posts:
- New Year 2008 And the year 2007 has gone by and into the...
- A 2008 love? story! Once there was a guy, enjoying life, doing whatever he...
- Math.Round Math.Round has been improved in C#. Consider the below piece...
- C#: Null coalescing operator C# has a ?? operator, which is called the ‘Null...
- C#: Calculate Age in Years, Month and Days Today I was given the task of finding the age...
Tags: C#, implicit casting, Programming