XmlSerializer - There was an error reflecting type

C#.NetXmlSerialization.Net 2.0

C# Problem Overview

Using C# .NET 2.0, I have a composite data class that does have the [Serializable] attribute on it. I am creating an XMLSerializer class and passing that into the constructor:

XmlSerializer serializer = new XmlSerializer(typeof(DataClass));

I am getting an exception saying:

> There was an error reflecting type.

Inside the data class there is another composite object. Does this also need to have the [Serializable] attribute, or by having it on the top object, does it recursively apply it to all objects inside?

C# Solutions

Solution 1 - C#

Look at the inner exception that you are getting. It will tell you which field/property it is having trouble serializing.

You can exclude fields/properties from xml serialization by decorating them with the [XmlIgnore] attribute.

XmlSerializer does not use the [Serializable] attribute, so I doubt that is the problem.

Solution 2 - C#

Remember that serialized classes must have default (i.e. parameterless) constructors. If you have no constructor at all, that's fine; but if you have a constructor with a parameter, you'll need to add the default one too.

Solution 3 - C#

I had a similar problem, and it turned out that the serializer could not distinguish between 2 classes I had with the same name (one was a subclass of the other). The inner exception looked like this:

'Types BaseNamespace.Class1' and 'BaseNamespace.SubNamespace.Class1' both use the XML type name, 'Class1', from namespace ''. Use XML attributes to specify a unique XML name and/or namespace for the type.

Where BaseNamespace.SubNamespace.Class1 is a subclass of BaseNamespace.Class1.

What I needed to do was add an attribute to one of the classes (I added to the base class):


Note: If you have more layers of classes you need to add an attribute to them as well.

Solution 4 - C#

Also be aware that XmlSerializer cannot serialize abstract properties.. See my question here (which I have added the solution code to)..

XML Serialization and Inherited Types

Solution 5 - C#

Most common reasons by me:

 - the object being serialized has no parameterless constructor
 - the object contains Dictionary
 - the object has some public Interface members

Solution 6 - C#

All the objects in the serialization graph have to be serializable.

Since XMLSerializer is a blackbox, check these links if you want to debug further into the serialization process..

Changing where XmlSerializer Outputs Temporary Assemblies

HOW TO: Debug into a .NET XmlSerializer Generated Assembly

Solution 7 - C#

If you need to handle specific attributes (i.e. Dictionary, or any class), you can implement the IXmlSerialiable interface, which will allow you more freedom at the cost of more verbose coding.

public class NetService : IXmlSerializable
    #region Data

        public string Identifier = String.Empty;

        public string Name = String.Empty;

        public IPAddress Address = IPAddress.None;
        public int Port = 7777;


    #region IXmlSerializable Implementation

        public XmlSchema GetSchema() { return (null); }

        public void ReadXml(XmlReader reader)
            // Attributes
            Identifier = reader[XML_IDENTIFIER];
            if (Int32.TryParse(reader[XML_NETWORK_PORT], out Port) == false)
            throw new XmlException("unable to parse the element " + typeof(NetService).Name + " (badly formatted parameter " + XML_NETWORK_PORT);
            if (IPAddress.TryParse(reader[XML_NETWORK_ADDR], out Address) == false)
            throw new XmlException("unable to parse the element " + typeof(NetService).Name + " (badly formatted parameter " + XML_NETWORK_ADDR);

        public void WriteXml(XmlWriter writer)
            // Attributes
            writer.WriteAttributeString(XML_IDENTIFIER, Identifier);
            writer.WriteAttributeString(XML_NETWORK_ADDR, Address.ToString());
            writer.WriteAttributeString(XML_NETWORK_PORT, Port.ToString());

        private const string XML_IDENTIFIER = "Id";

        private const string XML_NETWORK_ADDR = "Address";

        private const string XML_NETWORK_PORT = "Port";


There is an interesting article, which show an elegant way to implements a sophisticated way to "extend" the XmlSerializer.

The article say:

> IXmlSerializable is covered in the official documentation, but the documentation states it's not intended for public use and provides no information beyond that. This indicates that the development team wanted to reserve the right to modify, disable, or even completely remove this extensibility hook down the road. However, as long as you're willing to accept this uncertainty and deal with possible changes in the future, there's no reason whatsoever you can't take advantage of it.

Because this, I suggest to implement you're own IXmlSerializable classes, in order to avoid too much complicated implementations.

...it could be straightforward to implements our custom XmlSerializer class using reflection.

Solution 8 - C#

I just got the same error and discovered that a property of type IEnumerable<SomeClass> was the problem. It appears that IEnumerable cannot be serialized directly.

Instead, one could use List<SomeClass>.

Solution 9 - C#

I've discovered that the Dictionary class in .Net 2.0 is not serializable using XML, but serializes well when binary serialization is used.

I found a work around here.

Solution 10 - C#

I recently got this in a web reference partial class when adding a new property. The auto generated class was adding the following attributes.

	[System.Xml.Serialization.XmlElementAttribute(Order = XX)]

I needed to add a similar attribute with an order one higher than the last in the auto generated sequence and this fixed it for me.

Solution 11 - C#

I too thought that the Serializable attribute had to be on the object but unless I'm being a complete noob (I am in the middle of a late night coding session) the following works from the SnippetCompiler:

using System;
using System.IO;
using System.Xml;
using System.Collections.Generic;
using System.Xml.Serialization;

public class Inner
	private string _AnotherStringProperty;
	public string AnotherStringProperty 
      get { return _AnotherStringProperty; } 
      set { _AnotherStringProperty = value; } 

public class DataClass
	private string _StringProperty;
	public string StringProperty 
       get { return _StringProperty; } 
       set{ _StringProperty = value; } 
	private Inner _InnerObject;
	public Inner InnerObject 
       get { return _InnerObject; } 
       set { _InnerObject = value; } 

public class MyClass
	public static void Main()
			XmlSerializer serializer = new XmlSerializer(typeof(DataClass));
			TextWriter writer = new StreamWriter(@"c:\tmp\dataClass.xml");
			DataClass clazz = new DataClass();
			Inner inner = new Inner();
			inner.AnotherStringProperty = "Foo2";
			clazz.InnerObject = inner;
			clazz.StringProperty = "foo";
			serializer.Serialize(writer, clazz);
			Console.Write("Press any key to continue...");


I would imagine that the XmlSerializer is using reflection over the public properties.

Solution 12 - C#

Sometime, this type of error is because you dont have constructur of class without argument

Solution 13 - C#

I had a situation where the Order was the same for two elements in a row

[System.Xml.Serialization.XmlElementAttribute(IsNullable = true, Order = 0, ElementName = "SeriousInjuryFlag")]

.... some code ...

[System.Xml.Serialization.XmlElementAttribute(IsNullable = true, Order = 0, ElementName = "AccidentFlag")]

When I changed the code to increment the order by one for each new Property in the class, the error went away.

Solution 14 - C#

I was getting the same error when I created a property having a datatype - Type. On this, I was getting an error - There was an error reflecting type. I kept checking the 'InnerException' of every exception from the debug dock and got the specific field name (which was Type) in my case. The solution is as follows:

    public Type Type { get; set; }

Solution 15 - C#

Also note that you cannot serialize user interface controls and that any object you want to pass onto the clipboard must be serializable otherwise it cannot be passed across to other processes.

Solution 16 - C#

I have been using the NetDataSerialiser class to serialise my domain classes. NetDataContractSerializer Class.

The domain classes are shared between client and server.

Solution 17 - C#

[System.Xml.Serialization.XmlElementAttribute("strFieldName", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]


string [] strFielsName {get;set;}

Solution 18 - C#

I had the same issue and in my case the object had a ReadOnlyCollection. A collection must implement Add method to be serializable.

Solution 19 - C#

I have a slightly different solution to all described here so far, so for any future civilisation here's mine!

I had declared a datatype of "time" as the original type was a TimeSpan and subsequently changed to a String:

[System.Xml.Serialization.XmlElementAttribute(DataType="time", Order=3)]

however the actual type was a string

public string TimeProperty {
    get {
        return this.timePropertyField;
    set {
        this.timePropertyField = value;

by removing the DateType property the Xml can be serialized

public string TimeProperty {
    get {
        return this.timePropertyField;
    set {
        this.timePropertyField = value;


All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionleoraView Question on Stackoverflow
Solution 1 - C#LamarView Answer on Stackoverflow
Solution 2 - C#Jeremy McGeeView Answer on Stackoverflow
Solution 3 - C#Dennis CallaView Answer on Stackoverflow
Solution 4 - C#Rob CooperView Answer on Stackoverflow
Solution 5 - C#Stefan MichevView Answer on Stackoverflow
Solution 6 - C#Gulzar NazimView Answer on Stackoverflow
Solution 7 - C#LucaView Answer on Stackoverflow
Solution 8 - C#jkokorianView Answer on Stackoverflow
Solution 9 - C#Charlie SaltsView Answer on Stackoverflow
Solution 10 - C#LepardUKView Answer on Stackoverflow
Solution 11 - C#DarrenView Answer on Stackoverflow
Solution 12 - C#Esperento57View Answer on Stackoverflow
Solution 13 - C#Jeremy BrownView Answer on Stackoverflow
Solution 14 - C#Iqra.View Answer on Stackoverflow
Solution 15 - C#Phil WrightView Answer on Stackoverflow
Solution 16 - C#peterkaView Answer on Stackoverflow
Solution 17 - C#Kiran.BakwadView Answer on Stackoverflow
Solution 18 - C#Curious DevView Answer on Stackoverflow
Solution 19 - C#chxzyView Answer on Stackoverflow