Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent calling Public constructors except for XML Serializer [duplicate]

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?

like image 871
Ian Avatar asked Nov 26 '25 17:11

Ian


1 Answers

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.

like image 145
Adrian Godong Avatar answered Nov 29 '25 07:11

Adrian Godong



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!