Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 347569
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 12, 20262026-05-12T11:16:59+00:00 2026-05-12T11:16:59+00:00

I would like to XML serialize an object that has (among other) a property

  • 0

I would like to XML serialize an object that has (among other) a property of type IModelObject (which is an interface).

public class Example
{
    public IModelObject Model { get; set; }
}

When I try to serialize an object of this class, I receive the following error:
“Cannot serialize member Example.Model of type Example because it is an interface.”

I understand that the problem is that an interface cannot be serialized. However, the concrete Model object type is unknown until runtime.

Replacing the IModelObject interface with an abstract or concrete type and use inheritance with XMLInclude is possible, but seems like an ugly workaround.

Any suggestions?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-12T11:16:59+00:00Added an answer on May 12, 2026 at 11:16 am

    This is simply an inherent limitation of declarative serialization where type information is not embedded within the output.

    On trying to convert <Flibble Foo="10" /> back into

    public class Flibble { public object Foo { get; set; } }
    

    How does the serializer know whether it should be an int, a string, a double (or something else)…

    To make this work you have several options but if you truly don’t know till runtime the easiest way to do this is likely to be using the XmlAttributeOverrides.

    Sadly this will only work with base classes, not interfaces. The best you can do there is to ignore the property which isn’t sufficient for your needs.

    If you really must stay with interfaces you have three real options:

    Hide it and deal with it in another property

    Ugly, unpleasant boiler plate and much repetition but most consumers of the class will not have to deal with the problem:

    [XmlIgnore()]
    public object Foo { get; set; }
    
    [XmlElement("Foo")]
    [EditorVisibile(EditorVisibility.Advanced)]
    public string FooSerialized 
    { 
      get { /* code here to convert any type in Foo to string */ } 
      set { /* code to parse out serialized value and make Foo an instance of the proper type*/ } 
    }
    

    This is likely to become a maintenance nightmare…

    Implement IXmlSerializable

    Similar to the first option in that you take full control of things but

    • Pros
      • You don’t have nasty ‘fake’ properties hanging around.
      • you can interact directly with the xml structure adding flexibility/versioning
    • Cons
      • you may end up having to re-implement the wheel for all the other properties on the class

    Issues of duplication of effort are similar to the first.

    Modify your property to use a wrapping type

    public sealed class XmlAnything<T> : IXmlSerializable
    {
        public XmlAnything() {}
        public XmlAnything(T t) { this.Value = t;}
        public T Value {get; set;}
    
        public void WriteXml (XmlWriter writer)
        {
            if (Value == null)
            {
                writer.WriteAttributeString("type", "null");
                return;
            }
            Type type = this.Value.GetType();
            XmlSerializer serializer = new XmlSerializer(type);
            writer.WriteAttributeString("type", type.AssemblyQualifiedName);
            serializer.Serialize(writer, this.Value);   
        }
    
        public void ReadXml(XmlReader reader)
        {
            if(!reader.HasAttributes)
                throw new FormatException("expected a type attribute!");
            string type = reader.GetAttribute("type");
            reader.Read(); // consume the value
            if (type == "null")
                return;// leave T at default value
            XmlSerializer serializer = new XmlSerializer(Type.GetType(type));
            this.Value = (T)serializer.Deserialize(reader);
            reader.ReadEndElement();
        }
    
        public XmlSchema GetSchema() { return(null); }
    }
    

    Using this would involve something like (in project P):

    public namespace P
    {
        public interface IFoo {}
        public class RealFoo : IFoo { public int X; }
        public class OtherFoo : IFoo { public double X; }
    
        public class Flibble
        {
            public XmlAnything<IFoo> Foo;
        }
    
    
        public static void Main(string[] args)
        {
            var x = new Flibble();
            x.Foo = new XmlAnything<IFoo>(new RealFoo());
            var s = new XmlSerializer(typeof(Flibble));
            var sw = new StringWriter();
            s.Serialize(sw, x);
            Console.WriteLine(sw);
        }
    }
    

    which gives you:

    <?xml version="1.0" encoding="utf-16"?>
    <MainClass 
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:xsd="http://www.w3.org/2001/XMLSchema">
     <Foo type="P.RealFoo, P, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null">
      <RealFoo>
       <X>0</X>
      </RealFoo>
     </Foo>
    </MainClass>
    

    This is obviously more cumbersome for users of the class though avoids much boiler plate.

    A happy medium may be merging the XmlAnything idea into the ‘backing’ property of the first technique. In this way most of the grunt work is done for you but consumers of the class suffer no impact beyond confusion with introspection.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I would like to serialize an object to XML inside Android. Any libs suggested?
I would like to serialize my object with many values as string(xml) into user
I have a model that I would like to serialize to an xml with
I would like to know which dependency described in my pom.xml brings a transitive
I have an ActiveRecord model that I would like to convert to xml, but
Currently, we use a giant configuration object that is serialized to/from XML. This has
I want to serialize my object to xml and then to a string. public
I'm attempting to serialize an object but I would like to exclude one of
I would like to create XML Schema for this chunk of xml, I would
I would like to create an XML-based website. I want to use XML files

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.