Instead of explicitly declaring the variable of a specific type ,in the case of implicitly typed variable compiler determines the type of the variable.For example to declare a variable of int type we use the following declaration
int x=1;
in this case we are explicitly declaring variable of an int type.We can write the same declaration using implicit variable as:
var x=1;
var keyword is used to declare implicitly typed variables.
There are few important points to consider when using an implicitly typed variable:
It is mandatory to assign an initial value to implicitly typed variable.For example we can not write the following
var x;
Implicit variable just means that the compiler will determine the type of the variable.The type of the variable is determined at the compile time.So its just a matter of syntax rather than having any impact on the performance.
Implicitly typed variables can be declared only at the method scope.We can not declare implicit variable at the
class scope.
Implicitly typed variables can be used at the following scopes:
- to declare a variable in a method.
- as a initialisation variable in for & foreach loop.
- and in the using() statement.
For example the following are valid uses of implicitly typed variable.
public void Hello() { var x = 1; for (var y = 1; y <= 5;y++ ) { Console.WriteLine("Hello! {0}", y); } string[] array=new string[]{"A","B","C","D"}; foreach(var item in array) { Console.WriteLine(item); } }
In the case of anonymous types we have to use implicit variable as we do not know the type of an anonymous type
We can assign an anonymous type to an implicitly typed variable as:
var obj = new { Name = "Ashish", Id = 1, Subject = "Computers" };
We can not declare variable obj of any other type such as string or int since that can not point to an anonymous type.
Implicitly typed arrays
We can declare implicitly typed arrays in which the type of the array is determined by the array elements.
//array of integers var arrInts = new[] { 1, 2, 3, 4 }; //array of strings var arrStr = new[] { "A","B","C","D" };
It is important to understand that all the elements in an implicitly typed array must be of the same type.Following is not a valid array and will cause compilation error.
var arrInts = new[] { 1, "A",.1,true };
Implicitly typed variables in C# means that the type of the variable is determined by the compiler.It’s just another way of declaring the same variable.