and has 0 comments
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!

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

Comments

Be the first to post a comment

Post a comment