C# 3. 0 has introduced a new keyword “var” which allows us to declare a new variable.
As we were previously writing
int x = 100;
string y = “fortunate”;
But now with the keyword var, we can write like this
var x = 100;
var y = “fortunate”;
In this case the type is implicitly reference from the type used in the right hand side of the expression.
Some of the rules we need to follow while using var keyword.
1. we have to assign a value at the same line of the declaration of variable using var keyword.
Example:
var x;
x = 100; This is wrong.
var x = 100; This is right.
2. Initializer has to be a expression, not an object or collection or null.
If we want to declare an array or multiple variable declaration then we can write in a slightly different syntax as we were writing before.
Example:
var add = new [] { 1, 2, 3 , 4};