“Everyone knows that debugging is twice as hard as writing a program in the first place. So if you’re as clever as you can be when you write it, how will you ever debug it?”
– Brian Kernighan (the K of the essential K&R C book)
Month: March 2008
Anonymous Types in C# 3.0
For a long time, the var keyword has been the domain of only wholly dynamically typed languages. In fact, some people from the strongly-typed camp have considered the use of var as “hacky”, even though C#-ians have been able to treat everything as an object all along. Granted, it is not exactly the same and there is the whole boxing and unboxing thing to deal with, but I wanted to include full disclosure.
Now however, dynamic languages are all the rage and people are finding good uses for a generic variable type. To harness that power, one of the things done in C# 3.0 was the creation of Anonymous Types. Examine the code below and its output.
var blogPost = new { Name = "Anonymous Types in C# 3.0", Author = "Pete Shearer", Category = "Code Tips" }; Console.WriteLine(blogPost.Name); Console.WriteLine(blogPost.Author); Console.WriteLine(blogPost.Category);
By declaring my variable blogPost with the var keyword, I have created a dynamic variable. Now, after the new keyword and inside the curly braces, I declare a few properties and set their values. Behind the scenes, the compiler has declared a new object, given it a temporary name, and set the values in “traditional” fashion. It is even smart enough that if I declared another var with that definition, it wouldn’t redefine the anonymous type.
Within the anonymous type, the object remains strongly typed. Consider the following alteration to the code:
var blogPost = new { Name = "Anonymous Types in C# 3.0", Author = "Pete Shearer", Category = "Code Tips", Date = new DateTime(2008, 3, 27) }; Console.WriteLine(blogPost.Date.GetType());
The compiler inferred the type from the object placed into it. I know that I said new DateTime there, but it would have worked for any type that I put into that property. This new feature certainly affords developers a new level of flexibility. Enjoy.