views:

370

answers:

2

Is there a way to specify that a [Flags] enumeration field in a class should be serialized as the string representation (e.g. "Sunday,Tuesday") rather than the integer value (e.g. 5)?

To be more specific, when returning the following SomeClass type in a web service, I want to get a string field named "Days" but I'm getting a numeric field.

[Flags]
public enum DaysOfWeek
{
    Sunday = 0x1,
    Monday = 0x2,
    Tuesday = 0x4,
    Wednesday = 0x8,
    Thursday = 0x10,
    Friday = 0x20,
    Saturday = 0x40
}
[DataContract]
public class SomeClass
{
    [DataMember]
    public DaysOfWeek Days;
}
+1  A: 

No, but you could define your own "enum" by creating a struct that does the same thing,

public struct MyDayOfWeek
{
    private int iVal;
    private bool def;

    internal int Value
    {
        get { return iVal; }
        set { iVal = value; }
    }
    public bool Defined
    {
        get { return def; }
        set { def = value; }
    }
    public bool IsNull { get { return !Defined; } }

    private MyDayOfWeek(int i)
    {
       iVal = i;
       def = true;
    }           

    #region constants
    private const int Monday = new MyDayOfWeek(1);
    private const int Tuesday = new MyDayOfWeek(2);
    private const int Wednesday = new MyDayOfWeek(3);
    private const int Thursday = new MyDayOfWeek(4);
    private const int Friday = new MyDayOfWeek(5);
    private const int Saturday = new MyDayOfWeek(6);
    private const int Sunday = new MyDayOfWeek(7);
    #endregion constants

    public override string ToString()
    {
        switch (iVal)
        {
            case (1): return "Monday";
            case (2): return "Tuesday";
            case (3): return "Wednesday";
            case (4): return "Thursday";
            case (5): return "Friday";
            case (6): return "Saturday";
            case (7): return "Sunday";
        }
    }
}
Charles Bretana
+1  A: 

I don't know about DataContractSerializer, but with XmlSerializer it would be serialized as "Sunday Tuesday". I'm not a WCF expert, but I think I read somewhere that you can specify that XmlSerializer must be used instead of DataContractSerializer

Thomas Levesque