Search code examples
c#enumsbinary-serialization

Are Enums binary serialized as numbers or as text - I want to rename them


Are Enums binary serialized as numbers or as text - I want to rename them.

Example:

[Flags]
public enum VerticalAlignment : byte
{
    None = 0,
    Centered = 1,
    Top = 2,
    Bottom = 4,
    Stretch = 8,
    All = Centered | Top | Bottom | Stretch
}

Solution

  • It depends on the serializer you are using.

    Here is code that uses the DataContractSerializer

    var serializer = new DataContractSerializer(typeof (VerticalAlignment));
    
    var alignment = VerticalAlignment.Centered;
    
    using (var stream = File.Create("serialize.txt"))
    {
        serializer.WriteObject(stream, alignment);
        stream.Close();
    }
    

    This will serialize the data as XML, which uses the enum's name and not the value. The contents of the "serialize.txt" file are as follows:

    <Program.VerticalAlignment xmlns="http://schemas.datacontract.org/2004/07/ConsoleApplication2">Centered</Program.VerticalAlignment>
    

    If you want to do binary serialization, you can use the BinaryFormatter class:

    var serializer = new BinaryFormatter();
    
    var alignment = VerticalAlignment.Centered;
    
    using (var stream = File.Create("serialize.txt"))
    {
        serializer.Serialize(stream, alignment);
        stream.Close();
    }
    

    This will write the following to our serialization file:

    Binary serialization

    To test if name or value is used, we can rename the field and see if what gets written to file is different. First, we rename the enum field:

    [Flags]
    public enum VerticalAlignment : byte
    {
        None = 0,
        CenteredDummy = 1,
        Top = 2,
        Bottom = 4,
        Stretch = 8,
        All = CenteredDummy | Top | Bottom | Stretch
    }
    

    Now, if we examine the data that was written to file, we can see that the contents are the same:

    Binary serialization

    We thus now know for sure that the enum value is used and not the key.