Joseph Albahari & Ben Albahari have posted an article with the top ten LINQ myths, if you’re new to LINQ its definitely worth a read.
Category Archives: LINQ
New features in .Net 3.5 – Anonymous Types and Implicitly Typed Local Variables
Anonymous Types and Implicitly Typed Local Variables are two new features to the .Net 3.5 framework that work hand in hand and are used mainly with LINQ.
Anonymous Typing allows you to create a class without explictly defining the class, for example say you needed a class that contained the properties FirstName and LastName but you were only going to use it inside a single method and you didn’t want to define a class just for a one off usage.
Using anonymous typing you could create the class as follows:
var person = new {FirstName = "John", LastName = "Smit"}
Implicitly Typed Local Variable allows variables to be declared without having to specify the type at design-time. The strong-type assigned to the variable is inferred at compile-time from the initialization expression. This gives you some of the benefits of a dynamic type with the advantages of compile time checking.
So if the following Implicitly Typed Local Variables were declared:
(The var keyword denotes an Implicitly Typed Local Variable)
var person = new {FirstName = "John", LastName = "Smit"}
var num = 5;
var str = “Example”;
The compiler will know that the variable person is an object with the properties FirstName and LastName, and that num is an integer and str is a string. Basically whatever is on the right hand side of the equal sign defines the type of the variable. Once the variable has been declared it is type safe, so you won’t be able to assign the incorrect type to it or call members on it that don’t exist, in those cases a compile time error will occur.
The major use for Anonymous Types and Implicitly Typed Local Variables is with LINQ, when performing a LINQ query you may want to return information from multiple objects into a single object, now instead of having to create a class defining the properties you want to return from the query you can use Anonymous Types and Implicitly Typed Local Variables.
For example:
var cities = from city in Cities
join state in States on city.State equals state
select new
{
CityName = city.Name,
StateName = state.Name
};
In this example I only want to retrieve the city name and state name, but the properties I want are on two objects so I create a new anonymous type which is assigned to an implicitly typed local variable.
There are a couple of important restrictions when using the var keyword:
- The declaration must have an initializer that the compiler can resolve to a type definition.
- The initializer expression cannot evaluate to null. The compiler must be able to determine the type.
- A type called var cannot be in the same scope, otherwise it is used.
- The var keyword must only be used for local variable declaration.
Disclaimer: This post is based on Orcas CTP June 2007