Tuesday, November 11, 2008

How to return anonymous types from .Net 3.5 methods or how to cast objects to anonymous types

I have found this great link in Tomáš Petříček's blog which gives a very simple and elegant solution to casting to an anonymous type.

Short story shorter:

// Cast method - thanks to type inference when calling methods it
// is possible to cast object to type without knowing the type name
T Cast<T>(object obj, T objOfTypeT)
return (T)obj;

So simple! You see that the objOfTypeT parameter is never used, but the type infered from it is!

Correct usage:Cast(obj,anonObj)
Incorrect usage:Cast(obj,anonObj.GetType())