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.
- They can't be initialized as null.
- They need to be declared and initialized in the same statement
- They can't be used as a member of the class.
Comments
Post a Comment