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:
Post a Comment