Enum Serialization as Integer or Literal

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
 
S

Simon Tamman

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
 
M

Michael Bray

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
 
S

Simon Tamman

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!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top