As posted by Alex James on Meta-Me blog.
T CastByExample
So earlier today I was lamenting that an anonymous type can't be
shared between functions with Wes Dyer, when he said "Well actually they can..."
Cue me learning something cool.
The first step is to create a seemingly innocent method:
public static T CastByExample<T>(this object o, T example) { return (T) o; }
static object GetAnonymousType() { return new { FullName = "Cosmo Kramer" }; }
object o = GetAnonymousType(); //get the original anonymous type back again var v = o.CastByExample(new { FullName = "" }); //Use the properties of the anonymous type initialized in another //function directly !! Console.WriteLine(v.FullName);
This works because when an anonymous type is used the compiler first checks that one with the same signature (i.e. all fields are the same name and type) hasn't already been used. If one has the same CLR type is used.
Hence if you pass in an example that is the same shape as the original anonymous type to the CastByExample
Nifty huh?
3 comments:
Great!!
Except that you lose type checking. Eg. if your example object has different signature, you'll get runtime error.
Nice post. You may be interested in my post regarding anonymous and querying with LINQ.
http://activeengine.wordpress.com/2010/09/19/persistent-anonymoustypes-and-querying-with-linq/
Post a Comment