4

I have two classes:

namespace Something
{
    [Serializable]
    public class Spec
    {
        public string Name { get; set; }

        [XmlArray]
        public List<Value> Values { get; set; }
    }

    [Serializable]
    public class Value
    {
        public string Name { get; set; }

        public short StartPosition { get; set; }

        public short EndPosition { get; set; }

        public Value(string name, short startPosition, short endPosition)
        {
            Name = name;
            StartPosition = startPosition;
            EndPosition = endPosition;
        }
    }
}

When I try to serialize

var spec = new Spec();
spec.Name = "test";
spec.Values = new List<Value> { new Value("testing", 0, 2) };

var xmls = new XmlSerializer(spec.GetType());    
xmls.Serialize(Console.Out, spec);

I get an error:

InvalidOperationException

There was an error reflecting type 'Something.Spec'

Using a list of string I don't have any problems. Am I missing some attribute?

BrunoLM
  • 97,872
  • 84
  • 296
  • 452
  • 2
    Try looking at that exception you get, notice that it says "see inner exception for more details", and the inner exception says: "...Value cannot be serialized because it does not have a parameterless constructor". – Lasse V. Karlsen Feb 27 '11 at 18:32

2 Answers2

7

The Value class needs to have a default constructor if you want it to be serializable. Example:

public class Value
{
    public string Name { get; set; }
    public short StartPosition { get; set; }
    public short EndPosition { get; set; }
}

Also not that you don't need the [Serializable] attribute for XML serialization and it is completely ignored by the XmlSerializer class.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • In fact, the InnerException of the exception he got mentions this particular fact, no parameterless constructor. – Lasse V. Karlsen Feb 27 '11 at 18:32
  • @Lasse I completely forgot to check the inner exception, thanks. I was testing here, the default constructor needs to exist but it is not used for anything. So I made it thrown an exception, I need the values to be setted, a "default value" is invalid. – BrunoLM Feb 27 '11 at 18:36
  • thanks for your clear answer and for telling me about the `Serializable` attribute that is not needed by XML serialization. I actually didn't know that. :P – BrunoLM Feb 27 '11 at 18:38
  • @Bruno: The parameterless constructor will be used on deserialization. – Lasse V. Karlsen Feb 27 '11 at 19:46
0

Could it be that your Value type doesn't have a constructor that can be used to create an instance when deserialising?

Matthew Abbott
  • 60,571
  • 9
  • 104
  • 129