Question

I get an error on this code (//THIS LINE). The error says: cannot be serialized because they do not have parameterless constructors.

public static void SchrijfKlanten(Klant klant, string pad) {
    using (FileStream file = File.Open(pad, FileMode.OpenOrCreate)) {
    XmlSerializer xml = new XmlSerializer(klant.GetType()); //THIS LINE
    xml.Serialize(file, klant);
    }
}

How can i solve this?

Was it helpful?

Solution

The Serializer Class need a parameter-less constructor so that when it is deserializing it a new instance can be created. After that it copies every public property taken from the serialized data.

You can easily make the constructor private, if you want to avoid creating it without parameters.

EX:

using System;
using System.IO;
using System.Xml.Serialization;

namespace App
{
    public class SchrijfKlanten
    {
        public SchrijfKlanten(Klant klant, string pad)
        {

            using (FileStream file = File.Open(pad, FileMode.OpenOrCreate))
            {
                XmlSerializer xml = new XmlSerializer(klant.GetType()); //THIS LINE

                xml.Serialize(file, klant);
            }
        }

        private SchrijfKlanten() { }



        // cut other methods
    }
    [Serializable()]
    //Ensure there is a parameter less constructor in the class klant
    public class Klant
    {
        internal Klant()
        {
        }

        public string Name { get; set; }

        public static String type { get; set; }
         public static Type IAm { get; set; }
    }
}

OTHER TIPS

You should add parameterless constructor to class Klant:

class Klant
{
  public Klant()
  {
     //Any logic if you have
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top