Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping two identical enumeration with different namespaces

I've two identical C# enumeration defined like these:

public enum ArrivalToleranceEnum
{
    ZERO,
    QUARTERHOUR,
    HALFHOUR,
    ONEHOUR,
    TWOHOURS,
}

public enum ArrivalTolerance {

    /// <remarks/>
    ZERO,

    /// <remarks/>
    QUARTERHOUR,

    /// <remarks/>
    HALFHOUR,

    /// <remarks/>
    ONEHOUR,

    /// <remarks/>
    TWOHOURS,
}

ArrivalTolerance is defined in an external library and in my program I want to use a local enumaration ArrivalToleranceEnum so I need to convert these two types. How can I do this? I've tried to do this by end (using a switch) but it's very tedius and not very time saving because I've other much bigger enumeration I need to convert.

like image 206
Federico Avatar asked Nov 08 '13 10:11

Federico


People also ask

Can two enum names have the same value?

Two enum names can have same value. For example, in the following C program both 'Failed' and 'Freezed' have same value 0.

Can enum names have spaces?

Like any other variable, enums cannot use spaces in the names.

Can enums be inherited C#?

C# enumerations are value data type. In other words, enumeration contains its own values and cannot inherit or cannot pass inheritance.

Where should enums be defined C#?

In the C# language, enum (also called enumeration) is a user-defined value type used to represent a list of named integer constants. It is created using the enum keyword inside a class, structure, or namespace.


1 Answers

Enum values are represented by integer constants. If the underlying enum constants are the same, just cast:

(ArrivalToleranceEnum)(int)ArrivalTolerance.HALFHOUR

If they are not the same, you can automate the mapping using reflection code or one of the static members of the Enum class. That is more tedious and much slower, though.

like image 109
usr Avatar answered Oct 03 '22 05:10

usr