Design without a default constructor

I want to restrict the creation of an object using the default constructor. Because I have a view as shown below:

class Program { static void Main(string[] args) { BaseClass bc = new BaseClass("",""); XmlSerializer xml = new XmlSerializer(typeof(BaseClass)); StreamWriter sw = new StreamWriter(File.Create("c:\\test.txt")); xml.Serialize(sw,bc); sw.Flush(); sw.Close(); } } [Serializable] public class BaseClass { public string UserName, Password; // I don't want to create default constructor because of Authentication public BaseClass(string _UserName, string _Password) { UserName = _UserName; Password = _Password; f_Authenticate(); } private void f_Authenticate() { } } public class DerivedClass:BaseClass { public DerivedClass(string _UserName, string _Password) : base(_UserName, _Password) { } } 

This is normal. But when I make BaseClass for Serializable, it will throw this error: Unhandled Exception: System.InvalidOperationException: ConsoleApplication1.BaseC lass cannot be serialized because it does not have a parameterless constructor.

Now my project is crashing because I need to have Username , Password parameters, but the default constructor destroys my construction ....

What should I do?

+7
source share
3 answers

Create your own default constructor

 private DerivedClass() { // code } 

The serial number will make the call successfully even if it is closed

+12
source

The deserialization class of your instances requires a constructor without parameters to create an instance, but you do not need to implement a public constructor - it is enough to have a private or internal constructor if it does not need parameters.

By the way, you can also use the DataContractSerializer , which does not require a constructor without parameters and also creates XML; this is always my main choice :-)

+11
source
  • Have you tried to create a private constructor without parameters?

  • If there is a need for public, you can always comment that it should not be used (not the best solution)

You also need to create properties in the Serializable class. Variables are not counted and will not be read or written during serialization / deserialization

+1
source

All Articles