Question

I have a simple type that explicitly implemets an Interface.

public interface IMessageHeader
{
    string FromAddress { get; set; }
    string ToAddress   { get; set; }
}

[Serializable]
public class MessageHeader:IMessageHeader
{
  private string from;
  private string to;

  [XmlAttribute("From")]
  string IMessageHeade.FromAddress
  {
    get { return this.from;}
    set { this.from = value;}
  }

 [XmlAttribute("To")]
 string IMessageHeade.ToAddress
 {
    get { return this.to;}
    set { this.to = value;}
 }
}

Is there a way to Serialize and Deserialize objects of type IMessageHeader??

I got the following error when tried

"Cannot serialize interface IMessageHeader"

Was it helpful?

Solution

You cannot serialize IMessageHeader because you can't do Activator.CreateInstance(typeof(IMessageHeader)) which is what serialization is going to do under the covers. You need a concrete type.

You can do typeof(MessageHeader) or you could say, have an instance of MessageHeader and do

XmlSerializer serializer = new XmlSerializer(instance.GetType())

OTHER TIPS

No, because the serializer needs a concrete class that it can instantiate.

Given the following code:

XmlSerializer ser = new XmlSerializer(typeof(IMessageHeader));

IMessageHeader header = (IMessageHeader)ser.Deserialize(data);

What class does the serializer create to return from Deserialize()?

In theory it's possible to serialize/deserialize an interface, just not with XmlSerializer.

Try adding IXmlSerializable to your IMessageHeader declaration, although I don't think that will work.

From what I recall, the .net xml serializer only works for concrete classes that have a default constructor.

The issue stems from the fact that you can't deserialize an interface but need to instantiate a concrete class.

The XmlInclude attribute can be used to tell the serializer what concrete classes implement the interface.

You can create an abstract base class the implements IMessageHeader and also inherits MarshalByRefObject

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top