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 7833741
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 2, 20262026-06-02T12:52:16+00:00 2026-06-02T12:52:16+00:00

I have a class that has a property that is defined as interface. Users

  • 0

I have a class that has a property that is defined as interface.
Users of my class can assign to this property any class implementation that implements the interface.
I want to be able to load this class state from a textual file on disk. Users should be able to manually modify the xml file, in order to control the application’s operation.

If I try to serialize my class, it tells me I cannot serialize an interface.
I understand that the serializer has no knowledge about the structure of the property’s class, knowing only that it implements an interface.

I would have expected it to call GetType on the member, and reflect into the structure of the actual class. Is there a way to achieve this?
Is there another way to implement my requirement?

Edit: Clarifying my intentions:
Lets say I have this class:

class Car
{
IEngine engine
}
class ElectricEngine : IEngine 
{
int batteryPrecentageLeft;
}
class InternalCombustionEngine : IEngine 
{
int gasLitersLeft;
}

and the class user has a class with

Car myCar = new Car();
myCar.Engine = new ElectricEngine() {batteryPrecentageLeft= 70};

When I serialize the class myCar, I expect the the xml to resemble this:

<Car>
<Engine>
<ElectricEngine>
<batteryPrecentageLeft>70</batteryPrecentageLeft>
</ElectricEngine>
<Engine>
</Car>
  • 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-06-02T12:52:17+00:00Added an answer on June 2, 2026 at 12:52 pm

    Based on @Jens solution I have created a serializer that does what I need. Thanks Jen.
    Here is the code:

    public class RuntimeXmlSerializerAttribute : XmlIgnoreAttribute { }
    
    public class RuntimeXmlSerializer
    {
        private Type m_type;
        private XmlSerializer m_regularXmlSerializer;
    
        private const string k_FullClassNameAttributeName = "FullAssemblyQualifiedTypeName";
    
        public RuntimeXmlSerializer(Type i_subjectType)
        {
            this.m_type = i_subjectType;
            this.m_regularXmlSerializer = new XmlSerializer(this.m_type);
        }
    
        public void Serialize(object i_objectToSerialize, Stream i_streamToSerializeTo)
        {
            StringWriter sw = new StringWriter();
            this.m_regularXmlSerializer.Serialize(sw, i_objectToSerialize);
            XDocument objectXml = XDocument.Parse(sw.ToString());
            sw.Dispose();
            SerializeExtra(i_objectToSerialize,objectXml);
            string res = objectXml.ToString();
            byte[] bytesToWrite = Encoding.UTF8.GetBytes(res);
            i_streamToSerializeTo.Write(bytesToWrite, 0, bytesToWrite.Length);
        }
    
        public object Deserialize(Stream i_streamToSerializeFrom)
        {
            string xmlContents = new StreamReader(i_streamToSerializeFrom).ReadToEnd();
            StringReader sr;
            sr = new StringReader(xmlContents);
            object res = this.m_regularXmlSerializer.Deserialize(sr);
            sr.Dispose();
            sr = new StringReader(xmlContents);
            XDocument doc = XDocument.Load(sr);
            sr.Dispose();
            deserializeExtra(res, doc);
            return res;
        }
    
        private void deserializeExtra(object i_desirializedObject, XDocument i_xmlToDeserializeFrom)
        {
            IEnumerable propertiesToDeserialize = i_desirializedObject.GetType()
                .GetProperties().Where(p => p.GetCustomAttributes(true)
                    .FirstOrDefault(a => a.GetType() ==
                        typeof(RuntimeXmlSerializerAttribute)) != null);
            foreach (PropertyInfo prop in propertiesToDeserialize)
            {
                XElement propertyXml = i_xmlToDeserializeFrom.Descendants().FirstOrDefault(e =>
                    e.Name == prop.Name);
                if (propertyXml == null) continue;
                XElement propertyValueXml = propertyXml.Descendants().FirstOrDefault();
                Type type = Type.GetType(propertyValueXml.Attribute(k_FullClassNameAttributeName).Value.ToString());
                XmlSerializer srl = new XmlSerializer(type);
                object deserializedObject = srl.Deserialize(propertyValueXml.CreateReader());
                prop.SetValue(i_desirializedObject, deserializedObject, null);
            }
        }
    
        private void SerializeExtra(object objectToSerialize, XDocument xmlToSerializeTo)
        {
            IEnumerable propertiesToSerialize =
                objectToSerialize.GetType().GetProperties().Where(p =>
                    p.GetCustomAttributes(true).FirstOrDefault(a =>
                        a.GetType() == typeof(RuntimeXmlSerializerAttribute)) != null);
            foreach (PropertyInfo prop in propertiesToSerialize)
            {
                XElement serializedProperty = new XElement(prop.Name);
                serializedProperty.AddFirst(serializeObjectAtRuntime(prop.GetValue(objectToSerialize, null)));
                xmlToSerializeTo.Descendants().First().Add(serializedProperty); //TODO
            }
        }
    
        private XElement serializeObjectAtRuntime(object i_objectToSerialize)
        {
            Type t = i_objectToSerialize.GetType();
            XmlSerializer srl = new XmlSerializer(t);
            StringWriter sw = new StringWriter();
            srl.Serialize(sw, i_objectToSerialize);
            XElement res = XElement.Parse(sw.ToString());
            sw.Dispose();
            XAttribute fullClassNameAttribute = new XAttribute(k_FullClassNameAttributeName, t.AssemblyQualifiedName);
            res.Add(fullClassNameAttribute);
    
            return res;
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a class that has a property that I need to stub. I
I have a class that has the following property that is generated by the
I have a Menu class that has a IQueryable property called WebPages. In the
I have a class called Question that has a property called Type. Based on
I have come across a class that has an immutable property: MyObject[] allObjs The
I have a serializable Message class that has a Data As Object property that
I have a class, called DateField , that has a string Value property. If
I've got a class that has a read-only property defined that is actually a
I have a class that has an inner struct/class (I have decided which yet,
I have a class that has a method: -(NSInteger) getCityCountForState:(NSString *)state CityArray:(NSMutableArray *)cityArray {

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.