views:

40

answers:

3

Lets say I have business class:

public class Foo
{
   public int Prop1 {get;set;}
   public int Prop2 {get;set;}

   public Foo(int prop1, int prop2)
   {
      this.Prop1 = prop1;
      this.Prop2 = prop2;
   }

   public Foo()
   {
     throw new NotImplementedException();
   }
}

The business class is only valid if both properties are set. Therefore I could ensure implementing the parameterless constructor and throw a NotImplementedException if someone tries to instanciate the class with the parameterless constructor.

But now I want to be able to serialize/deserialize my class. For the deserilization process I need the default constructor, which musn't throw the NotImplementedExeption anymore.

Is there a way to find out whether a create an instance of my class with the default constructor or whether the object is being deserialized?

Let's assume I have no valid default values for both properties.

How could I solve this situation?

A: 

Hide the default constructor using protected modifier.

Read More

Vash
That wont work if using XmlSerialization.
leppie
A: 

Binary deserialization will NOT call any constructors, AFAIK.

leppie
A: 

If you implement ISerializable then you will have the deserialisation happen through the constructor you need to use for that.

If you implement IXmlSerializable and the serialisation is by XmlSerialization, then you will have the deserialisation happen through the ReadXml method defined by that interface.

If you implement IDeserializationCallback, then you will have your implementation of OnDeserialization called after the object is constructed. That might be too late for your purposes, but if its enough, then it is probably the easiest to add to an already-existing class.

Jon Hanna