Possible Duplicate:
How to XML deserialize an object of Unknown Type?
I’ve just started playing with serializing and deserializing.
I have a model of type Person, with only 2 properties (Name and Age), I can serialise to XML. When it comes to deserialise, as far as I know, I have to tell the compiler that the type is Person. With the world of generic T, this seems counter productive. I would have thought I could establish the object as a ‘InMemoryOnly’ object (if you can imagine it) where the object is created at run time, as is it’s parameters/fields/properties etc, all based upon the XML. Maybe like an anonymous type; I appreciate that the C# compiler would have to ignore this during design time and that we’d lose intellisense but as all objects are passed to memory any way, I can’t see why it would fail at run time. Or maybe this would be possible with Reflection?
Any way, that is what I’m trying to do, deserialise from XML to a generic object. Is this possible with C#?
EDIT Just found a dupe so the question now is about why can’t C# (.NET) do this? I know the answer is probably “because it doesn’t” but my question is COULD it be possible or would be more trouble than it’s worth for the programmer?
The reason for this is, as far as I know, to accomplish this means the serialise and de-serialize has to know the type (in this case, Person). So, if the serailise and deserialize happen over WCF (where serialize and serialize happen in different assemblies) then the Person object has to be duplicated (and this is against the DRY principle)
The WCF sample does not demonstrate a valid reason to do this.
You simply could – and can! – put the Person class in an assembly that is used by both the server and the client. That’s how I do it when using WCF.
If you don’t want to do this, Visual Studio offers to automatically generate the types used in the service when you add a service reference.
In both cases, you have to update the
Personclass in one place only.