Anonymous Types in C# 3.0 Needed for LINQ
by David Hayden ( C# .NET Developer ), Filed: C# 3.0 Examples and Tutorials
I have discussed new features in C# 3.0 in the following articles in no particular order:
and now we move on to Anonymous Types, which are also very important to LINQ.
If we go back to my simple Customer Class that I have been using throughout my examples:
public class Customer
{
private int _id;
public int Id
{
get { return _id; }
set { _id = value; }
}
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
private string _city;
public string City
{
get { return _city; }
set { _city = value; }
}
public Customer() {}
}
We can use Object Initialization Expressions in C# 3.0 to create a list of customers as such:
List<Customer> listOfCustomers =
new List<Customer> {
{ Id = 1, Name="Dave", City="Sarasota" },
{ Id = 2, Name="John", City="Tampa" },
{ Id = 3, Name="Abe", City="Miami" }
};
I can create a query for this list using LINQ, which essentially selects all customers but does not include the Id in the resultset. We also redefine Name as FirstName in the resultset by specifying FirstName = c.Name.
var query = from c in listOfCustomers
select new {FirstName = c.Name,c.City};
We then run this query, returning the results to customers:
var customers = query.ToList();
When I look at the default debugger visualizer information on customers, I see the following data
The local variable customers contains a newly defined anonymous type that has a FirstName and a City. We now have a var keyword to specify it as an implicity typed local variable created at runtime because we cannot explicity reference the type from our code. Doing a GetType() on the customers variable gives us a little information about its type, but for our purposes, we really don't care:
System.Collections.Generic.List`1[[ExtensionMethods.Program+
<Projection>f__1, LINQApplication, Version=1.0.0.0,
Culture=neutral, PublicKeyToken=null]]
Conclusion
Because LINQ creates types on the fly based on our queries, we need C# 3.0 to include Anonymous Types and Implicity Typed Local Variables. I will talk more about Implicitly Typed Local Variables in another tutorial.
by David Hayden ( C# .NET Developer ), Filed: C# 3.0 Examples and Tutorials