![]() |
VOOZH | about |
Implicitly typed variables are those variables that are declared without specifying the .NET type explicitly. In an implicitly typed variable, the type of the variable is automatically deduced at compile time by the compiler from the value used to initialize the variable.
The implicitly typed variable concept is introduced in C# 3.0. The implicitly typed variable is not designed to replace the normal variable declaration, it is designed to handle some special-case situations like LINQ(Language-Integrated Query).
Question: Why it is termed Local?
Answer: It is not allowed to use var as a parameter value or return type in the method or define it at the class level etc. because the scope of the implicitly typed variable is local.
Compile-Time Error:
prog.cs(10,2): error CS0825: The contextual keyword `var' may only appear within a local variable declaration
var ivariable = 10; var ivalue = 20, a = 30; // invalidVar b;
b -= 39; var ivalue; // invalid var value = null; // invalid// Not allowed
var data = { 23, 24, 10};
// Allowed
var data = new int [] {23, 34, 455, 65};// It will give error because
// the type of the value is different
// one is of string type and another
// one is of int type
var value = "sd"
value = new int[]{1, 2, };Type of 'a' is : System.Int32 Type of 'b' is : System.String Type of 'c' is : System.Double Type of 'd' is : System.Boolean
Height of triangle is: 20 Base of the triangle is: 13 Area of the triangle is: 130
Note: Implicitly typed local variables can be used as a local variable in a function, in foreach, and for loop, as an anonymous type, in LINQ query expression, in using statement etc.