New language feature in c# 3.0 Implicitly typed local variables

Hi

Another of the new feature in The C# 3.0 will be the declaration of implicitly typed local variables. This means that we can declare any local variable with the type var and it type will be inferred from the expression that is used to declare it.

This means that if we declare a local variable with type var (and there is no type named var in the scope) the declaration becomes implicitly typed local variable. Hence the following lines of code will be possible and correct in C# 3.0

var int1 = 10;

var decimal = 2.45;

var string = “Vikram Lakhotia”;

var intArray = new int[] {1,4,8,0,3};

The declaration above are equivalent to the declaration with int, double, string and int[] respectively. But there are also some important restrictions to be remembered here.

  • The decelerator must have an initializer with it.
  • The initializer must be an expression. The initializer cannot be an object or collection initializer by itself, but it can be a new expression that includes an object or collection initializer.
  • The initializer expression compile time type cannot be null type.
  • If the local variable declaration includes multiple decelerators, the initializer must all have the same compile-time type

Hence we cannot declare a variable in the following fashion.

var xyz;

var somearray = {1,2,3};

var nullValue = null;

Also remember if there is already a type named var in the scope than the type inferred would the var type and a warning will also be generated.

Thanks
Vikram


Share this post   Email it |  digg it! |  reddit! |  bookmark it!

Feedback

Please post your comments:

Name:  
Email (optional): Your email address will not be posted.
URL (optional):
Comments: HTML will be ignored, URLs will be converted to hyperlinks  
Enter the text you see in the box:
 
Copyright © 2006 - 2009 Vikram Lakhotia