EmitDefaultValue and the DataContractSerializer

Often times when serializing an object to XML, you may want to include empty elements with their default values. This is the default behavior of the .NET Framework’s DataContractSerializer, but it can be toggled by using the EmitDefaultValue property in the DataMember attribute on a class’s properties. EmitDefaultValue has a default value of true, meaning it will include empty elements with their default value. Setting this property to false causes empty elements to be excluded.

Here’s a complete example:

namespace Serialization.EmitDefaultValue
{
    [DataContract]
    public class Human
    {
        [DataMember]
        public string Name { get; set; }
    }

    [DataContract]
    public class HumanNoDefault
    {
        [DataMember(EmitDefaultValue = false)]
        public string Name { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var prog = new Program();
            prog.Run();
        }

        public void Run()
        {
            SerializeToConsole<Human>();
            SerializeToConsole<HumanNoDefault>();

            Console.ReadLine();
        }

        public void SerializeToConsole<T>() where T : new()
        {
            using (var ms = new MemoryStream())
            {
                var h = new T();
                var serializer = new DataContractSerializer(typeof(T));
                serializer.WriteObject(ms, h);
                ms.Seek(0, SeekOrigin.Begin);
                var sr = new StreamReader(ms);
                Console.WriteLine("{0}:{1}{2}{1}", typeof(T).Name, Environment.NewLine, sr.ReadToEnd());
            }
        }
    }
}

And the output (note that the Name element is excluded in the second XML):

Human:
<Human xmlns="http://schemas.datacontract.org/2004/07/Serialization.EmitDefaultValue" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><Name i:nil="true"/></Human>

HumanNoDefault:
<HumanNoDefault xmlns="http://schemas.datacontract.org/2004/07/Serialization.EmitDefaultValue" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"/>
Advertisement

Author: Adam Prescott

I'm enthusiastic and passionate about creating intuitive, great-looking software. I strive to find the simplest solutions to complex problems, and I embrace agile principles and test-driven development.

Leave a comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: