Crudler
Crudler

Reputation: 2286

serializing enum and addind description

I have an enum as such:

public enum DriveConfig
{
    [Description("4X2")]
    FOURXTWO=0,

    [Description("4x4")]
    FOURXFOUR=1,

    [Description("6x2")]
    SIXBYTWO=2,

    [Description("6x4")]
    SIXBYFOUR=3

}

And in my system I can get the description out nice and easy with something like this:

public static string GetDescriptionFromEnumValue(Enum value)
    {
        DescriptionAttribute attribute = value.GetType()
            .GetField(value.ToString())
            .GetCustomAttributes(typeof(DescriptionAttribute), false)
            .SingleOrDefault() as DescriptionAttribute;
        return attribute == null ? value.ToString() : attribute.Description;
    }

works really nicely.

But now i need to extend the system with webservices,so I am making dto's of my objects, and serializing them. straight forward. but how can I include the description on the other end?

I tried this

[DataContract]
public enum DriveConfigDto
{
    [Description("4X2")]
    [EnumMember]
    FOURXTWO=0,

    [Description("4x4")]
    [EnumMember]
    FOURXFOUR=1,

    [Description("6x2")]
    [EnumMember]        
    SIXBYTWO=2,

    [Description("6x4")]
    [EnumMember]
    SIXBYFOUR=3
}

but I cant access the description on the other end

Upvotes: 2

Views: 933

Answers (4)

Rene Niediek
Rene Niediek

Reputation: 147

before you add a service reference you have to reference the assemby in which the enum is definded in and add it to the reuse assembly list while adding the service reference.

Upvotes: 0

Serve Laurijssen
Serve Laurijssen

Reputation: 9733

If I understand correctly you can use the Value property of EnumMemberAttribute:

[DataContract]
public enum DriveConfigDto
{
    [EnumMember(Value="4X2")]
    FOURXTWO=0,

    [EnumMember]
    FOURXFOUR=1,

    [EnumMember]        
    SIXBYTWO=2,
}

The resulting XSD will look like:

<xs:simpleType name="">
<xs:restriction base="xs:string">
<xs:enumeration value="4X2"/>
<xs:enumeration value="FOURXFOUR"/>
<xs:enumeration value="SIXBYTWO"/>
</xs:restriction>
</xs:simpleType>

Upvotes: 1

flayn
flayn

Reputation: 5322

This will not work, as these attributes are not automatically serialized.

Upvotes: 1

Dennis
Dennis

Reputation: 37760

You can't do this in common case, because there can be non-.NET client for your web-service (hence, it knows nothing about attributes, because attributes are not a part of contract).

But if you're limited with .NET on client side, you can share contracts assembly between server and clients.

Upvotes: 0

Related Questions