Enum Serialization as Integer or Literal

  • Thread starter Thread starter Diego
  • Start date Start date
D

Diego

I have an Enum like this:

public enum DAYS
{
Monday = 1,
Tuesday = 2,
Wednesday = 3,
Thursday = 4,
Friday = 5,
Saturday = 6,
Sunday = 7
}


By default enumerations are de-/serilized (in XML) as literals, e.g.
<Tuesday>.

I would like to be able to de-/serialize the Enum as "literal"
(<Tuesday>) and as "integer" (<2>) depending on the user (runtime).

My first idea was XmlEnum, but it does not work runtime :-(

???

Thanks
 
Int is no problem.

DAYS day = (DAYS) 1; // that's monday

Strings are more iffy. You'll have to create a method that loops through all
of the enums until it finds a string match. Then you'll have to update it
every time you add something to the enum (groo).
It "might" be possible to get all the enums through reflection, although
i've never tried reflection on a primitive type like an enum, but you can
look it up to see if it is supported.

HTH

Simon
 
Simon Tamman said:
DAYS day = (DAYS) 1; // that's monday

Strings are more iffy. You'll have to create a method that loops
through all of the enums until it finds a string match. Then you'll
have to update it every time you add something to the enum (groo).
It "might" be possible to get all the enums through reflection,
although i've never tried reflection on a primitive type like an enum,
but you can look it up to see if it is supported.

If you are trying to convert a string to the equivalent Enum, look at
Enum.Parse. It does exactly that. No need to iterate over the Enum to
find a match.

-mdb
 
Awwww noooo way. I could have saved myself mucho time had I known that
earlier (although these days I usually avoid enums in favour of the state
pattern).
Thanks for the info!
 
Back
Top