1

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?

6
  • Add a parameterless constructor to your Klant type! Commented Dec 21, 2013 at 15:36
  • @nemesv How can i put those fields from my Klant in the XML file? Commented Dec 21, 2013 at 15:41
  • Check this answer out -stackoverflow.com/questions/267724/… Commented Dec 21, 2013 at 15:42
  • That solved my error. But how can I add my variables in the xml file without using parameters? Commented Dec 21, 2013 at 15:48
  • create two constructors. Commented Dec 21, 2013 at 16:00

2 Answers 2

1

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; }
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

What should be the method without parameters so that my variables get in the XML file?
SchrijfKlanten() as a private constructor.
That's not the problem, what code should be in the constructor public Klant() so that my variables get in the XML
No problem. I went back and did it in VS to ensure the syntax was correct.
0

You should add parameterless constructor to class Klant:

class Klant
{
  public Klant()
  {
     //Any logic if you have
  }
}

1 Comment

what code should be in the constructor public Klant() so that my variables get in the XML

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.