Thursday, February 4, 2010

Implicitly typed local variable in C#

Implicitly typed local variable is a variable that can be declared without specifying the .NET type explicity. The type of that variable will be inferred by the complier from the expression on the right side of initialization statement.

Examples:

var i = 5;

When the compiler sees this in the code, it tries to figure out the type of the variable based on the value you assigned it. Hence, if you call GetType() on i, the type returned is actually System.Int32.

The following will give you an error because the compiler can't figure out what type the variable is:

var i = null;

You have to initialize the variable with something that the compiler understands so it can figure out the type. Calling GetType() on firstName here would give you System.String:

var firstName = "David";

Limitations:

-> The declarator must include an initializer. Unlike normal declarations, you can’t declare the implicitly type variable without initializing.

-> The compile-time type of the initializer expression cannot be the null type.

-> If the local variable declaration includes multiple declarators, the initializers must all have the same compile-time type.The implicitly-type local variable cann’t be initialized with different types more than one time. You can’t assign the string to varaible “test” after initializing with integer value “1".

-> Cannot initialize an implicitly-typed local variable with an array initializer like var test = { 1, 2, 3 }; Can only use array initializer expressions to assign to array types, like a new expression var test1 = new[] { 1, 2, 3 };

-> an implicitly typed local variable cannot be Nullable variable which means the following syntax to create a Nullable variable in C# will not work with implicitly typed variables - var? age = null;

-> Implicit Typed Variable cannot be used as class members such as field. They can only be used as local variables inside methods.

0 comments: