Use of 'var' keywords in C#

This is the new feature in c# 3.0. This enables us to declare a variable whose type is implicitly inferred from the expression used to initialize the variable.
For eg.

 var age=10;

Because the initialization value(10)  of the variable age is integer type of age will be treated as integer type of variable. 
'var' keyword is used for two main reason's:

1. To limit redundant code:

Dictionary<string, List<int, bool>> myDictionary = new Dictionary<string,   List<int,bool>>();
By using 'var' keyword can be written as:

var myDictionary = new Dictionary<string, List<int,bool>>();

2.To support anonymous types

var car = new { Name = "ABC", Address= "XYZ" };

There are few limitation of the 'var' type of variables.
  1. They can't be initialized as null.
  2. They need to be declared and initialized in the same statement
  3. They can't be used as a member of the class. 

Comments

Popular posts from this blog

Enable HTTP Transport Security (HSTS) in IIS 7

When to use Truncate and Delete Command in SQL

Steps To Create New Project/Team On TFS