Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Copying Enumeration from one object to another

Tags:

c#

enums

I have two very similar but not identical C# objects. I am copying the values from one class to another.

Each class has some properties that expose an enumeration type. The inside of the enumerations are the same but the names are different e.g.

public enum EnumA
{
 A,
 B
} 

public EnumA EnumAProperty
{
 get{ return enumA;}
}

public enum EnumB
{
 A,
 B
} 

public EnumB EnumBProperty
{
 get{ return enumB;}
}

I want to assign the value returned from EnumBProperty to EnumAProperty is this possible?

like image 238
AJM Avatar asked Aug 11 '11 15:08

AJM


2 Answers

You can do via casting but I would not recommend it as it is fragile — if any of the enum members are reordered or new items added the result may not be what you expect.

EnumAProperty = (EnumA) EnumBProperty;

Even worse with the casting is if you have items in your source enum with no equivalent in the destination — below there are more colours than shapes:

enum Color { Red = 0, Yellow = 1, Blue = 2 };
enum Shape ( Square = 0, Triangle = 1 };

Color color = Color.Red;
Shape shape = (Shape) color;

shape could end up with the value 2 even though this value is not defined.

Instead, I'd suggest you use a switch statement to map:

EnumAProperty = ConvertToA(EnumBProperty);

...

private static EnumA ConvertToA(EnumBProperty b)
{
    switch (b)
    {
        case EnumB.Flannel: return EnumA.HandTowel;
        case EnemB.Vest: return EnumA.UnderShirt;
        ...
        default: throw new ArgumentOutOfRangeException("b");
    }
}
like image 116
Paul Ruane Avatar answered Sep 19 '22 18:09

Paul Ruane


Each enum member has a corresponding integer value.
By default, these values are assigned in ascending order, starting with 0.

If the order of the items in the enums (and thus their numeric values) are the same, you can just cast the numeric value to EnumB to get the EnumB member with the same value:

 EnumBProperty = (EnumB)(int)EnumAProperty;

If not, you need to re-parse it:

EnumBProperty = (EnumB)Enum.Parse(typeof(EnumB), EnumAProperty.ToString());
like image 29
SLaks Avatar answered Sep 19 '22 18:09

SLaks