Wednesday, 28 May 2008

.Net 3.5 -- C# 3.0 -- Local Type Inference



Local variable type inference is a feature in C# 3.0 where you can use the var keyword instead of explicitly specifying the type of a variable. The C# 3.0 compiler makes the type of the variable match the type of the right side of the assignment. There are places when using C# 3.0 where we must do type inference when declaring variables; there is no other way, so we must cover this topic here.

LINQ query expressions (and many standard query operators) return a type of IEnumerable for some type T. When using LINQ, it is often convenient to make the type parameter be an anonymous type. An anonymous type's name is automatically generated by the compiler, but hidden from the program. If you write a query expression that creates an anonymous type, then the results of the query expression are an IEnumerable of the anonymous type. To declare a variable to hold the results of such a query expression it is necessary to use type inference.



One of the goals of C# 3.0 is to make the language cleaner and smoother. C# 2.0's major innovation was undoubtly generics, but using these introduced quite a bit of "noise" when declaring and instantiating generic types.

It is important to understand that the var keyword does not mean “Variant” and does not indicate that the variable is loosely typed, or late-bound. It just means that the compiler determines and assigns the most appropriate type.
The var keyword may be used in the following contexts:
On local variables (variables declared at method scope) as shown in the previous example.
In a for initialization statement.
for(var x = 1; x < file =" new">
foreach(var item in list){...}
using (var file = new StreamReader("C:\\myfile.txt")) {...}

శశిధర్

No comments: