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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 2, 20262026-06-02T16:09:35+00:00 2026-06-02T16:09:35+00:00

Trying to serialize a union-like data-type. There is an enum field indicating the type

  • 0

Trying to serialize a union-like data-type. There is an enum field indicating the type of data stored in the union, and a variety of possible field types.

The desired result is DataContractSerializer produced XML which contains just the enum, and the relevant field.

Possible solutions, none of which have been attempted yet, are:

  • Use a custom serializer and mark the union properties with a custom attribute, similar to this question. The custom serializer would strip out the members not required.
  • Use ISerializationSurrogate and serialize a different object which just contains the relevant data.
  • Don’t use separate fields in the union, use one object field (this could be used as part of the implementation of the ISerializationSurrogate approach).
  • Other… ?

For example:

[DataContract]
public class WCFTestUnion
{
    public enum EUnionType
    {
        [EnumMember]
        Bool,
        [EnumMember]
        String,
        [EnumMember]
        Dictionary,
        [EnumMember]
        Invalid
    };

    EUnionType unionType = EUnionType.Invalid;

    bool boolValue = true;
    string stringValue = "Hello";
    IDictionary<object, object> dictionaryValue = null;

    // Could use custom attribute here ?
    [DataMember]
    public bool BoolValue
    {
        get { return this.boolValue; }
        set { this.boolValue = value; }
    }

    // Could use custom attribute here ?
    [DataMember]
    public string StringValue
    {
        get { return this.stringValue; }
        set { this.stringValue = value; }
    }

    // Could use custom attribute here ?
    [DataMember]
    public IDictionary<object, object> DictionaryValue
    {
        get { return this.dictionaryValue; }
        set { this.dictionaryValue = value; }
    }

    [DataMember]
    public EUnionType UnionType
    {
        get { return this.unionType; }
        set { this.unionType = value; }
    }
} // Ends class WCFTestUnion

Test

    class TestSerializeUnion
    {
        internal static void Test()
        {
            Console.WriteLine("===TestSerializeUnion.Test()===");

            WCFTestUnion u = new WCFTestUnion();
            u.UnionType = WCFTestUnion.EUnionType.Dictionary;
            u.DictionaryValue = new Dictionary<object, object>();
            u.DictionaryValue[1] = "one";
            u.DictionaryValue["two"] = 2;

            System.Runtime.Serialization.DataContractSerializer serialize = new System.Runtime.Serialization.DataContractSerializer(typeof(WCFTestUnion));
            System.IO.Stream stream = new System.IO.MemoryStream();

            serialize.WriteObject(stream, u);

            stream.Seek(0, System.IO.SeekOrigin.Begin);
            byte[] buffer = new byte[stream.Length];
            int length = checked((int)stream.Length);
            int read = stream.Read(buffer, 0, length);
            while (read < stream.Length)
            {
                read += stream.Read(buffer, 0, length - read);
            }

            string xml = Encoding.Default.GetString(buffer);

            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            doc.LoadXml(xml);

            System.Xml.XmlTextWriter xmlwriter = new System.Xml.XmlTextWriter(Console.Out);
            xmlwriter.Formatting = System.Xml.Formatting.Indented;

            doc.WriteContentTo(xmlwriter);
            xmlwriter.Flush();

            Console.WriteLine();
        }
    } // Ends class TestSerializeUnion

Output:

<WCFTestUnion xmlns="http://schemas.datacontract.org/2004/07/WCFTestServiceContracts" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
  <BoolValue>true</BoolValue>
  <DictionaryValue xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
    <a:KeyValueOfanyTypeanyType>
      <a:Key i:type="b:int" xmlns:b="http://www.w3.org/2001/XMLSchema">1</a:Key>
      <a:Value i:type="b:string" xmlns:b="http://www.w3.org/2001/XMLSchema">one</a:Value>
    </a:KeyValueOfanyTypeanyType>
    <a:KeyValueOfanyTypeanyType>
      <a:Key i:type="b:string" xmlns:b="http://www.w3.org/2001/XMLSchema">two</a:Key>
      <a:Value i:type="b:int" xmlns:b="http://www.w3.org/2001/XMLSchema">2</a:Value>
    </a:KeyValueOfanyTypeanyType>
  </DictionaryValue>
  <StringValue>Hello </StringValue>
  <UnionType>Dictionary</UnionType>
</WCFTestUnion>

Desired Output (only field being used is serialized, along with enum):

<WCFTestUnion xmlns="http://schemas.datacontract.org/2004/07/WCFTestServiceContracts" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
  <DictionaryValue xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
    <a:KeyValueOfanyTypeanyType>
      <a:Key i:type="b:int" xmlns:b="http://www.w3.org/2001/XMLSchema">1</a:Key>
      <a:Value i:type="b:string" xmlns:b="http://www.w3.org/2001/XMLSchema">one</a:Value>
    </a:KeyValueOfanyTypeanyType>
    <a:KeyValueOfanyTypeanyType>
      <a:Key i:type="b:string" xmlns:b="http://www.w3.org/2001/XMLSchema">two</a:Key>
      <a:Value i:type="b:int" xmlns:b="http://www.w3.org/2001/XMLSchema">2</a:Value>
    </a:KeyValueOfanyTypeanyType>
  </DictionaryValue>
  <UnionType>Dictionary</UnionType>
</WCFTestUnion>
  • 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-02T16:09:37+00:00Added an answer on June 2, 2026 at 4:09 pm

    You do have several options here. What you use depends on the complexity of this scenario (where else you have to do something like this, how often and in what ways you have to serialize this data, performance, etc.) Take a look at these options, ask away if you have more questions, but mostly, I recommend you just play and experiment with multiple strategies from the list below before picking one or a hybrid solution.

    • Use a data contract resolver. Provides a mechanism for dynamically mapping types to and from wire representations during serialization and deserialization, giving you flexibility to support far more types than you can out-of-the-box.

    • Use IObjectReference. You can have a class which implements and returns a reference to a different object after it has been deserialized.

    • Use a data contract surrogate. This is different from the serialization surrogates you’re referring to, but also similar. I think these might work out nicely for you

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

Sidebar

Related Questions

I'm trying to serialize a Type object in the following way: Type myType =
i am trying to serialize a field of my class. Withou it serialization is
I have some XML that I am trying serialize like so: string Value =
I am trying to serialize a .net object contains another data contract object as
I trying to serialize a custom type which holds a dictionary among other members.
I have been trying to serialize some json data in Silverlight. I am using
I am trying to serialize a list that contains non-system types. Below is my
I'm trying to serialize an object and the following SerializationException is thrown: Type 'System.Linq.Enumerable+d__71`1[[System.String,
I'm trying to serialize some data to xml in a way that can be
I'm trying to serialize a data structure and pass it to another report via

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.