Kristian Kristensen’s Blog

Serializing Enums in WCF

Posted in Code,Microsoft,WCF by Kristian Kristensen on the November 24th, 2007

I’ve been doing some development using WCF recently. A couple of days ago I experienced an odd problem. My service client would get an exception saying that the HTTP transport layer was unexpectedly closed. Debugging the service didn’t yield an immediate solution; the operation was executed, and returned successfully. So the problem was apparently after the return from the operation.

To try and get some perspective on the problem I configured diagnostics and tracing for my service. Fairly easy stuff, and it allows you to plug into all aspects of WCF. Using svctraceviewer.exe that gets installed with the framework you can easily analyze the trace and log files. Locating my operation execution in the log file I found the culprit. Apparently there was an error serializing an enum I was using to signal status messages. It hinted towards the EnumMemberAttribute, so I looked up the documentation for it.

Bottom line in order to serialize an enum you need to specify what value to serialize it to. I thought that it would use the default ToString representation when you decorated the enum with a DataContract attribute (which btw is also required), but apparently not. It makes sense to decouple the enum code from the actual serialized format going over the wire.
Later I read this post from Dare Obasanjo about code generation and web services in which he advises not to use enums in web service implementation. He points to a previous post of his regarding enums and web services. With this in mind it makes perfect sense having to specify the serialization value of the num. It helps decouple the client from future changes in the enum from the service side, and in that respect helps interoperability and future versioning.

  • If you like my writing you should subscribe to my RSS feed.

    One Response to 'Serializing Enums in WCF'

    Subscribe to comments with RSS or TrackBack to 'Serializing Enums in WCF'.

    1. Ken said,

      on January 24th, 2008 at 4:28 pm

      I was having a problem where the enum was not deserializing at all. The default (0) was always read no matter what was passed. I was about to go through and set the Value for all of my EnumMember attribs. I then had an idea. What if I set the DataMember using the enum to IsRequired?

      Well, NOW IT WORKS! No having to set the enum values or specify them in the EnumMember attrib.

      Weird though.

      Now I have to figure out why several other Datamembers are not being deserialized (notably my Int64 and DateTime typed members)


    Leave a Reply

    You must be logged in to post a comment.