Accessing C# Anonymous Type Objects

As the other answers have stated, you really shouldn’t do this. But, if you insist, then there’s a nasty hack known as “cast by example” which will allow you to do it. The technique is mentioned in a couple of articles, here and here. public void FuncB() { var example = new { Id = … Read more

A generic list of anonymous class

You could do: var list = new[] { o, o1 }.ToList(); There are lots of ways of skinning this cat, but basically they’ll all use type inference somewhere – which means you’ve got to be calling a generic method (possibly as an extension method). Another example might be: public static List<T> CreateList<T>(params T[] elements) { … Read more

Can anonymous class implement interface?

No, anonymous types cannot implement an interface. From the C# programming guide: Anonymous types are class types that consist of one or more public read-only properties. No other kinds of class members such as methods or events are allowed. An anonymous type cannot be cast to any interface or type except for object.

Dynamic Anonymous type in Razor causes RuntimeBinderException

Anonymous types having internal properties is a poor .NET framework design decision, in my opinion. Here is a quick and nice extension to fix this problem i.e. by converting the anonymous object into an ExpandoObject right away. public static ExpandoObject ToExpando(this object anonymousObject) { IDictionary<string, object> anonymousDictionary = new RouteValueDictionary(anonymousObject); IDictionary<string, object> expando = new … Read more