Skip to main content

The not so anonymous type

You can actually return an anonymous type from a method. Consider the following.

>public object GetMyDTO()
{
    return new { ID = 1, Name = "Mint", Url = "http://mint.litemedia.se" };
}

private T Cast<T>(object o, T type) { return (T)o; }

Now we can cast that object back to its anonymous type if we use type inference.

var schema = new { ID = 0, Name = string.Empty, Url = string.Empty };
var mySite = Cast(GetMyDTO(), schema);

Debug.WriteLine(mySite.Name);

This leads to the discussion on how anonymous that type really is. When will this break and could we accomplish a better solution with the dynamic keyword?

comments powered by Disqus