SYSK 283: Use Caution When Using ‘Short’ Data Type in Enumerated Types

Consider the following innocent looking code:

[System.Runtime.Serialization.DataContract]

public enum TestEnum : short

{

    [System.Runtime.Serialization.EnumMember] Undefined = 0,

    [System.Runtime.Serialization.EnumMember] TestType1 = 1,

    [System.Runtime.Serialization.EnumMember] TestType2 = 2,

}

[System.Runtime.Serialization.DataContract]

public class TestData

{

    private TestEnum _test = TestEnum.Undefined;

    [System.Runtime.Serialization.DataMember]

    public TestEnum Test

    {

        get { return _test; }

        set { _test = value; }

    }

}

 

Do you see any problems with it? Notice that TestEnum values are defined as short, not the default (integer) data type…

 

While the System.Runtime.Serialization.DataContractSerializer will serialize/de-serialize an instance of TestData class without any problems, System.Web.Script.Serialization.JavaScriptSerializer will throw an exception -- "Specified cast is not valid."

 

Try it yourself:

TestData d1 = new TestData();

d1.Test = TestEnum.TestType1;

System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();

string x = js.Serialize(d1);

 

Note: change the TestEnum to be int, and the problem is gone…