Possible Duplicate:
Why XML-Serializable class need a parameterless constructor
Does anyone know if it is possible to prevent calling of a public constructor from outside a range of assemblies?
What I'm doing is coming up with a class library that has XML serializable classes. These classes make no sense if constructed without setting various properties so I want to prevent that state.
I'm wondering if there is a way to prevent anyone calling my public constructor, and keep it there only for serialization?
Typically, I would create a public constructor with parameters that will make the object valid and create a public parameterless constructor with valid default values.
public foo() {
this.bar = -1;
}
public foo(int bar) {
this.bar = bar;
}
Private/internal constructor can be used depending on your situation, and you can create a Factory pattern that deals with object creation for external code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With