views:

1945

answers:

4

Possible Duplicate:
How do I serialize an enum value as an int?

Hi, all!

I'm wondering if there's a way to force the serialization of an enum value into its integer value, instead of its string representation.

To put you into context: We're using, in a web application that heavily relies on web services, a single baseclass for all our request headers, independantly of the type of request.

I want to add a Result field to the header, so we'll have a place to pass hints back to the calling app as to how the operation went on the web service side. We already have an enum declared to that effect, but since we have legacy apps that call on those web services that may not know about those enums, I'd like to send serialize those values as integers.

We've already had to cut down on the length of those headers by using the [XmlElement(ElementName = "string representationOfAttributeName")] because we occasionally exceeded IE maximum url length, and I wondered whether there's a similar Attributes to force the serialization of enum values into integers.

Anyone ever heard of such an attribute?

As ever, thanks for the help, Pascal

A: 

Oups!
Never mind; it already does serialize as an int!
:$

Pinpin
+2  A: 

Enums do serialize to ints. But generally, if you don't like the way one of your properties gets serialized to XML, you can just do this:

[XmlIgnore]
public MyThing MyThing { get; set; }

[XmlElement("MyThing")]
private string MyThingForSerialization
{
    get { return //convert MyThing to string; }
    set { MyThing = //convert string to MyThing; }
}
Matt Howells
Note that `MyThingForSerialization` has to be public. The XmlSerializer won't look at private fields/properties.
Miral
A: 

Enums do NOT serialize as int as default. I am using XMLSerializer to serialize a class and i have the same problem as described.

(The example of Matt Howells seems to work if you change the scope of MyThingForSerialization to public but i would like to see a better implementation cause this creates 1 extra public property)

Entrodus
+1  A: 

You can use the XmlEnumAttribute. See the article in:

http://geekswithblogs.net/claeyskurt/archive/2006/07/19/85667.aspx