Monday, May 24, 2010

Type Inference ( Implicitly typed variables)

To define any variable we have to tell the data type which declaring it. For e.g

string str = "Hello World";

This tells the compiler that str is of type string.

Microsoft has introduced new keyword “var” in.Net 3.5. This is similar to var in java script.  When any variable is declared as var then complier decides its data type at compile type based on the value assigned to that variable. This is known as type reference. For e.g.

image

You can see that it has detected str as string & allowing us to call all string functions.

Let’s take few more examples to under type inference

            var name = "Atul";

            var age = 26;

            var prog = new Program();

            Console.WriteLine("Name is of type " + name.GetType().Name);

            Console.WriteLine("Answer is of type " + age.GetType().Name);

            Console.WriteLine("Prog is of type " + prog.GetType().Name);

 

Output would be

image

Implicit type inference rules

1.  Variable need to initialize it while declaring it. For e.g. following code would not compile

 

// This would not compile

 var name;

 

2.       Initialization to null value is not allowed

        

// This would not compile

var name = null;

 

3.  Conditional operator can be used during initialization time for e.g.

 

            bool myCondition = false;

            var name = myCondition ? "a":"b";

 

4.  If conditional operator is used with initialization then the data type of if/else must be same. Following code would not work. Compiler would not be able to decide the data type of ‘name’

 

            // This would not compile

            bool myCondition = false;

            var name = myCondition ? "a": false;

 

5.  Type inference works with subtyping as well. For e.g.

 

class MyBase

{

}

 

class MyDerive : MyBase

{

}

 

bool myCondition = true;

         var myObj = myCondition ? new MyBase() : new MyDerive();

Console.WriteLine(myObj.GetType());

 

Output

image

6.       We can also use type inference with Arrays

 

// This will declare an array of type int32

var myArray = new []{1,2,3,4};

 

This will define an array integers.

Conclusion : Type inference is a nice feature where you do not have to explicitly mention the data type while declaring the variable. However it is not recommended to use ‘var’ keyword if you know the type. Basically new keyword is introduced to support LINQ where we don’t know the result type of the query.

No comments: