views:

1656

answers:

5

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"

A: 

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

Joel Coehoorn
A: 

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.

Brannon
A: 

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.

Jon
A: 

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.

Steve Morgan
+2  A: 

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())
Darren Kopp