Tuesday, August 16, 2011

Type Inference

To understand type inference, let us look at couple of lines of code.

var count = 1;
var output = "This is a string";
var employees = new EmployeesCollection();

In the above lines of code, the compiler sees the var keyword, looks at the assignment to count, and determines that it should be an Int32, then assigns 1 to it. When it sees that you assign a string to the output variable, it determines that output should be of type System.String. Same goes for employees collection object. As you would have guessed by now, var is a new keyword introduced in C# 3.0 that has a special meaning. var is used to signal the compiler that you are using the new Local Variable Type Inference feature in C# 3.0.

As an example, let us modify our string query example to use the var keyword.




string[] names = {"John", "Peter", "Joe", "Patrick", "Donald", "Eric"};
var namesWithFiveCharacters =
from name in names
where name.Length < 5
select name'
var lstResults = new List();
foreach(var name in namesWithFiveCharacters)
lstResults.Add(name);



As the above code shows, the variable namesWithFiveCharacters now uses the type "var" instead of IEnumerable. Using "var" is much more extensible since it tells the compiler to infer the type from the assignment. In this case, based on the results of the query, which is IEnumerable, the compiler will automatically assume that it is a variable of type IEnumerable.

If you run the code, it still produces the same output.
(http://www.15seconds.com/issue/060713.htm)

No comments: