Tuesday, June 22, 2010

Dynamic type simplifies returning an anonymous type from a function

Ever since Microsoft added anonymous types to C#, I've tried to use them in the manner that Microsoft themselves described: "Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to first explicitly define a type."

And, it seemed to me that one of the best uses for one of these "temporary" objects is as a return type from a function. Yet, Microsoft expressly designed anonymous types to not be usable as a return type. Sure, you could have the return type as Object, but then you could not cast it back as the type because it is "anonymous".

Here is a Blog Post the explains how to return an anonymous type using a casting function.

Now though it is much simpler. All you need to do is set the return value to "dynamic". Since the dynamic type is determined at run time instead of compile time, compiler type checking is bypassed. At run time, when dynamic variables are referenced, they then have their methods and properties verified. So you can, in code, reference a property without having the compiler knowing if the type actually has the property.

One caveat: This will only work within the same assembly. From a design standpoint, this makes sense. Why pass along an anonymous type between assemblies? It just does not make any sense. Inside a single assembly it is local and you are in full control, but between assemblies? You never know who is going to use it. You cannot assume that they would have any idea what is being returned.


Code Snippet



  1. static void Main(string[] args)

  2. {

  3. var d = ReturnAnonamoustype();

  4.  

  5. Console.WriteLine(d.Name);

  6. Console.Read();

  7. }

  8.  

  9. static dynamic ReturnAnonamoustype()

  10. {

  11. return new { Name = "Bob", Age = 50 };

  12. }



No comments: