Sunday, October 18, 2009

Using enums with NetDataContractSerializer

When using the NetDataContractSerializer in WCF you can run into troubles when serializing enum types. If you do not specify a zero value for the enum, and try to serialize/deserialize a collection (such as an IList) of enums, you will get a serialization exception stating that no '0' value for the enum was defined. Example: public enum ColorsNonZeroBased { Red = 1, Orange = 2, Green = 5 } When trying to serialize IList you get the following exception: System.Runtime.Serialization.SerializationException: Enum value '0' is invalid for type 'Bromo.TaskChannel.Test.ColorsNonZeroBased' and cannot be serialized. Ensure that the necessary enum values are present and are marked with EnumMemberAttribute attribute if the type has DataContractAttribute attribute.. The solution is to provide a zero value for the enum (which is probably the recommended solution), or you can add a [FlagsAttribute] to the enum.

1 comment:

Oscar Agreda said...

Great solution.. thank you very much

and cannot be serialized. Ensure that the necessary enum values are present and are marked with EnumMemberAttribute attribute if the type has DataContractAttribute attribute