Anony­mous types are use­ful, espe­cially in LINQ queries where you often want to iter­ate through an array of items and project them into some arbi­trar­ily shaped objects that are lit­tle more than sim­ple data con­tain­ers, using anony­mous types save you the has­sle of hav­ing to first declare those types which you will sim­ply throw away afterwards.

One thing you can’t eas­ily do with anony­mous types how­ever, is to return them from the method it’s declared in and use them else­where. Sure, you can return an instance of an anony­mous type as object, but that doesn’t make it any eas­ier to work with them as you don’t have access to any of the prop­er­ties on the anony­mous type. So what can you do in those cases?

Cast By Example

This is a nifty tech­nique which can deals with the above prob­lem, and all you need is a sim­ple method like this:

   1: public static T CastByExample<T>(this object o, T example) 

   2: { 

   3:     return (T) o; 

   4: }

You can then take an instance of an anony­mous type and cast it back to its orig­i­nal shape:

   1: static object GetAnonymousType() 

   2: { 

   3:     return new { FirstName = "Yan", Surname = "Cui", Age = 29 };

   4: }

   5:  

   6: ...

   7:  

   8: object o = GetAnonymousType();

   9:  

  10: // get the original anonymous type back again 

  11: var o2 = o.CastByExample(new { FirstName = "", Surname = "", Age = 0 });

  12:  

  13: // you can now use the properties on the original anonymous type freely

  14: Console.WriteLine(o2.FirstName);

This works, but only if the exam­ple is the exact shape as the orig­i­nal, oth­er­wise you’ll get an Invalid­Cas­tEx­cep­tion:

   1: // throws InvalidCastException

   2: // Unable to cast object of type '<>f__AnonymousType0`3[System.String,System.String,System.Int32]'

   3: // to type '<>f__AnonymousType1`2[System.String,System.String]'.

   4: var o2 = o.CastByExample(new { FirstName = "", Surname = "" });

Dynamic Pro­gram­ming

An alter­na­tive to using the Cast By Exam­ple tech­nique is to take advan­tage of the dynamic key­word intro­duced in C# 4, whilst this approach makes every­thing soooo easy, the trade off is that you lose intel­lisense support.

   1: // simply cast the returned object as a dynamic and off you go!

   2: var o = (dynamic)GetAnonymousType();

   3:  

   4: Console.WriteLine(o.FirstName);

Of course, if you try to use a prop­erty that isn’t defined on the anony­mous type then you’ll get an excep­tion at run­time, specif­i­cally the Run­time­BinderEx­cep­tion.

Part­ing Thoughts..

Both tech­niques can help make life eas­ier if on the rare occa­sion you need to return an anony­mous type from your method, but if you find your­self doing that fre­quently in your code then it’s prob­a­bly best to take a step back and rethink your over­all archi­tec­ture. Anony­mous types are con­fined to meth­ods by design, and for a good rea­son! If you’ve struc­tured your code cor­rectly fol­low­ing good OOP design prin­ci­ples then there should be very lit­tle need to ‘hack’ your way through using these tech­niques! So as a part­ing shot, please use these tech­niques with cau­tion and only when absolutely necessary!

Share

Leave a Reply