views:

472

answers:

3

I have a feeling this is a repost but I can't seem to find any good information about it. I was just wondering how serialization actually works (well actually deserialization). What I'm wondering is if say I have a property that is not actually backed by a private field; i.e.:

public string SomeProp {
   get {
      return GetValue("SomePropKey");
   }
   set{
      SetValue("SomePropKey", value);
   }
}

When I deserialize does the setter get called? The getter gets called on serialization because when I serialize the object the correct value is written to the output stream. I know this seems like a strange circumstance, but what is really going on? Or am I just over complicating this....

+7  A: 

It completely depends on the mechanism you are using for serialization.

If you are using XmlSerialization, then yes, the setter gets called.

If you are using data contract serialization (the DataContractSerialization) then the getter/setter will be called if you apply the DataMember attribute to the property (not to its backing field).

If you are using the original serialization mechanism in .NET (IFormatter implementation) then this scenario isn't possible, because it will only serialize values stored in fields.

casperOne
Thanks, we are using XmlSerialization. Sorry I didn't include that. And thank you again!
Adam Driscoll
A: 

Are you talking about XML Serialization, or 'regular' serialization (soap / binary), since -afaik- these 2 serialization techniques differ.

AFAIK, if you use the BinaryFormatter or SoapFormatter, the fields are serialized/deserialized, and not the properties.
On deserialization, I believe that the special 2-arg constructor which has the SerializationInfo & StreamingContext arguments is used.

But, nothing hinders you of taking control of the serialization process by implementing the ISerializable interface. Then, if you want that your value is set using your property, I think you can perfectly do so.

Frederik Gheysels
A: 

I know its not a direct answer to your question and you have already got the answer you were looking for. But I didn't want to withhold this. You can look at the Base Class Library sources using Reflector. It's an excellent way to understand more about the internals of the .net framework and to broaden your knowledge.

olle