Tuesday, October 08, 2013

Serializing list of enums in .NET

Recently I've been coding some WCF methods and I've got a strange exception during WCF message serialization. I needed to send list of enums to the WCF service. There are couple of ways to do that.
First solution is using [Flag] attribute to combine several enum values into one variable - but then you need to use powers of 2 for enum values. I couldn't do that because of the requirements and actual big number of that enums stored in current database. It would require writing and applying a lot of scripts just to correct old enum values in db.
Another way of doing that is by passing a list of enums. So I've decided to use that approach. But strangely I've encountered a little problem around that. Below is a sample code from WCF data contract:

 [DataContract]  
 public class SomeClass  
 {  
   [DataMember]  
   public List<SomeEnum> SomeEnums { get; set; }  
 }  

Looks pretty simple but if we will try to pass empty list of that values we'll encounter an below exception:
Enum value '0' is invalid for type 'SomeEnum' and cannot be serialized. Ensure that the necessary enum values are present and are marked with EnumMemberAttribute attribute if the type has DataContractAttribute attribute.
Code is valid. The problem is that during serialization .NET framework is trying to serialize empty list which has capacity set to something bigger than 0. So the solution is simple - we just need to set the capacity to 0 by using Count property.

 someObject.SomeEnums.Capacity = someObject.SomeEnums.Count;  

It's a shame that it isn't working like that out of the box. In my opinion .NET Framework should check that before serialization and do not throw any exception. Code is not doing something invalid so it shouldn't throw any exception.

No comments:

Post a Comment