Thursday, November 29, 2007

Anonymous Types: C# 3.0

Anonymous Types are a new feature available with C# 3.0 and VB 9. In fact one of many new features that is available with C# 3.0 or VB 9.0 (Visual Studio 2008, "Orcas"). This is a compiler feature not a framework feature. As with Implicitly Typed Local Variables, you only need the C# 3.0 or VB 9 compiler in order for your end users to use this functionality - not the .NET Framework 3.5. They go hand in hand with Implicitly Typed Local Variables. However, generally you will be using Visual Studio 2008 as who these days explicitly uses a command-line compiler to compile their code!!? Not many.

I have written an article on Implicitly Typed Local Variables, if you haven't read it yet, you can do so here.

Anonymous Types allow you to create an instance of a class without the need to write code for the class in the first place. Anonymous Types go hand in hand with LINQ and Implicitly Typed Local Variables. They must be coded in-line. Consider the following example:
new {Name="Simon Hart", Age=30, Married=True}
The above code needs to be assigned to a type. But what type? The type is anonymous! this where the other new feature of C# 3.0 known as Implicitly Typed Local Variables come into play by use of the new keyword - var.

So the above would look like the following when assigning to a Implicitly Typed Local Variable:
var person = new {Name="Simon Hart", Age=30, Married=True};
What happens when you run this code? Well the following image shows the types that have been inferred to their assumed types:
Clever stuff eh!? As you would expect the other properties; Married is of type boolean and Name is of type string.

I know what you're thinking, "why would I want to do this". Well the answer is for many reasons and in lots of places. Sometimes you create types that you are not too concerned about and the lifecyle is very short. Other times you have an designed an encapsulated type that will never be exposed to the outside world. In addition the power comes when using this with LINQ. You can use LINQ without Anonymous Types and in fact without Implicitly Typed Local Variables, but it makes your life a lot easier to use these new features. It allows you to craft you're own types at runtime, maybe based on what the user has requested. When you get to grips with LINQ, Anonymous Types are very powerful.

I will be publishing many articles on LINQ very soon..

No comments: