Posts Tagged ‘The type was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically’

PostHeaderIcon Serialization

Having just recently ran into some major serialization issues I’m going to list some of the errors and pitfalls that I ran into.

Some of the errors encountered

Error one
“<ClassName> is inaccessible due to its protection level. Only public types can be processed.”

It means that the Class you are trying to serialize is not marked as public and hence the serializor can not access it. Depending on the Class scope this may not be a problem e.g. the serialization code and the class are both in the same scope.

Error Two
“Cannot serialize member <Property Name> of type <Type> because it is an interface.”

It means that one of the members in your class is defined as an interface. An interface can never be serialized since the serializor will not know which instance of the interface to use.

Error Three
The type <Type> was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically.

This error is caused when trying to serialize an inherited class

E.g. the following example will cause this problem


public class Test
{
  private string _Field = "";
  public string Field
  {
    get { return _Field; }
    set { _Field = value; }
  }
}

public class TestInherited : Test
{
}

public class Container
{
  private Test ivField;
  public Test Field
  {
    get { return _Field; }
    set { _Field = value; }
  }
}

Container _Test = new Container();
_Test.Field = new TestInherited();

The issue is that the Container.Field is defined as Test but instantiated as TestInherited. Their are two solutions for this problem
1) Add the attribute [XmlInclude(typeof(TestInherited))] to the Test class
2) new XmlSerializer(typeof(Container), new Type[] { typeof(TestInherited) });

The second method is preferred. With the first method you have to decorate your base classes to which you may not always have access to, secondly the base class should not be aware of any class that inherits from it.