views:

61

answers:

4

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?

+1  A: 

Define "serialize." Serialization implies the ability to deserialize later, and if there is no defined class, there would be nothing to deserialize to. However, if you simply want the data to be placed in an XML file for retreival later, you could certainly do that.

Create an instance of your XML Document of choice (XmlDocument, XDocumnet, whatever) and build it that way (inserting your nodes and values as you go), then use basic File IO to save it somewhere. Or, if you're just trying to pass it between processes or somesuch, pass it as a MemoryStream or Byte[]

AllenG
+3  A: 

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.

JaredPar
A: 

Duplicate Can I serialize Anonymous Types as xml?

chilltemp
A: 

Only in a very general sense, in that there is nothing to stop you creating XML that represents an object and nothing to stop you creating an object whose state reflects some XML.

In the specific sense of directly supported by the framework, and resulting in an object of a type defined by an assembly, then no. By definition, an anonymous object isn't defined, that's what makes it anonymous.

Jon Hanna