Question

I have an enum

namespace Business
{
    public enum Color
   {
       Red,Green,Blue
    }
}


namespace DataContract
{
   [DataContract] 
   public enum Color
   {
       [EnumMember]
       Red,
       [EnumMember]
       Green,
       [EnumMember]
       Blue
    }
}

I have the same enum as a datacontract in WCF with same values. I need to convert the Business enum to the DataContract enum using a translator.

Hoe can I achieve this?

Was it helpful?

Solution

If you know both types at the time you need to do the conversion you can do something like:

Business.Color bc = Business.Color.Red;
DataContract.Color dcc = (DataContract.Color)Enum.Parse(typeof(DataContract.Color), bc.ToString())

OTHER TIPS

Below, a more elegant style as the framework code.

public static class Enum<T> where T : struct
{
    public static T Parse(string value)
    {
        return (T)Enum.Parse(typeof(T), value);
    }

    public static T Convert<U>(U value) where U : struct 
    {
        if (!value.GetType().IsInstanceOfType(typeof(Enum)))
           throw new ArgsValidationException("value");

        var name = Enum.GetName(typeof (U), value);
        return Parse(name);
    }
}

//enum declaration
...    
public void Main()
{
   //Usage example
   var p = Enum<DataContract.Priority>.Convert(myEntity.Priority);
}

And voilà!

You could use something like below:

public static class ColorTranslator
{
    public static Business.Color TranslateColor(DataContract.Color from)
    {
        Business.Color to = new Business.Color();
        to.Red = from.Red;
        to.Green = from.Green;
        to.Blue = from.Blue;

        return to;
    }

    public static DataContract.Color TranslateColor(Business.Color from)
    {
        DataContract.Color to = new DataContract.Color();
        to.Red = from.Red;
        to.Green = from.Green;
        to.Blue = from.Blue;

        return to;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top