Is there any way to serialize an anonymous type in .net? Normal XmlSerializer fails because the type has no parameterless constructor defined; and NetDataContractSeralizer fails becuase we can't tag DataContract or Serializable attribute to anonymous class.
So is there any clever way around or we just can't do it?
Yes it is possible to serialize an anonymous type. The easiest way that comes to mind is to create a wrapper object which implements ISerializable
and uses reflection to inspect an anonymous type for it's fields and serialize them as appropriate. It would be very ugly but would work.
However I think the more important question is
Is it possible to deserialize an anonymous type?
The answer to that is "Not in a general sense". Anonymous types are assembly specific types. So while it's possible to do in a specific manner for a specific anonymous type, it is not doable in the general sense and not between different assemblies since they are internal.