C# – XMLSerialization in C#

.netc++interfaceserialization

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"

Best 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())