Wednesday, February 4, 2009

Implicitly Typed Local Variable in C#

Confused…. Yes, now a local variable (method level variable) can be declared without declaring its type In Csharp 3.0, something new to Csharp. The type is then infered by the value assigned to it. Once you assign a value to such variable then it’s type is infered by the compiler and thus making it type safe. Following are the impliaction towards it uses.

1) Can only be defined in local scope (Mehtod level).

2) Declaration must follow var keyword i.e. var myVariable = (value | Expression). Please note that if you are declaring and assigning a var type with a literal then it is much wiser to use explicitly typed variable :) . Following are few valid declarations.

var myVar;

var myVar = row["SomeColumn"]; // Where row is of type DataRow and contains.

var myVar = 0; //Valid but since you know the type in advance it's not a good style use int myVar = 0;

var myVar = [Some expression];

3) Implicity type identification is not to be mixed up with Variant type in VB and Boxing and Generics in Dotnet. Variant is such a type whose type is variable or can be changed. Boxing and UnBoxing at the otherhand are performed at runtime and so does some part of Generic implementation is. At the other hand implicit type inference is completely compile time and doesn’t effect performance of your code. It is just that the compiler infer the type and then replace it in the declaration at the place of var keyword (just thinking abruptly). 

4) Initialization with null is not supported by these variable. i.e. you can’t use the following.

var myStringOrObject = null; //Invalid statement. No way for the compiler to infer.

if (someThingIsTrue)

    myStringOrObject = MyClass.MyMethodWhichReturnsObjects();

else if (someThingElseIsTrue)

    myStringOrObject = MyClass.MyMethodWhichReturnsStrings();

if(myStringOrObject == null) //Sequence of actions goes here.

else if (myStringOrObject is String) //Sequence of actions goes here.

else if (myStringOrObject is Object) //Sequence of actions goes here.

No comments: