Convert an Enum to Another Type of Enum

convert an enum to another type of enum

Using an extension method works quite neatly, when using the two conversion methods suggested by Nate:

public static class TheirGenderExtensions
{
public static MyGender ToMyGender(this TheirGender value)
{
// insert switch statement here
}
}

public static class MyGenderExtensions
{
public static TheirGender ToTheirGender(this MyGender value)
{
// insert switch statement here
}
}

Obviously there's no need to use separate classes if you don't want to. My preference is to keep extension methods grouped by the classes/structures/enumerations they apply to.

Converting one enum type to another by name

You can use Enum.Parse/Enum.TryParse:

A.UserType ut1 = A.UserType.Primary;
B.UserData data = new B.UserData();
data.UserType = Enum.TryParse(typeof(B.UserType), ut1.ToString(), true, out object ut2) ? (B.UserType)ut2 : B.UserType.Other;

A and B are just the namespace i have used to differentiate both enums. To simluate it i have used classes:

public class A
{
public enum UserType
{
Primary = 100001,
Secondary = 100002,
Other = 100003
}
}

public class B
{
public enum UserType
{
Primary,
Secondary,
Other
}

public class UserData
{
public UserType UserType { get; set; }
}
}

Transform one enum to another enum

In general, you can use write a function called lowercaseKeys() to transform the keys of any object to lowercase, and then assert that such a function returns a strongly typed result. The return type involves key remapping to make a mapped type where the string literal keys into their lowercase counterparts via the Lowercase intrinsic string manipulation type:

function lowercaseKeys<T extends object>(obj: T): { 
[K in keyof T as K extends string ? Lowercase<K> : K]: T[K]
} {
return Object.fromEntries(
Object.entries(obj).map(([k, v]) => [k.toLowerCase(), v])
) as any;
}

Again, this should work for any object:

const example = lowercaseKeys({ STR: "hello", NUM: Math.PI });
/* const example: {
str: string;
num: number;
} */
console.log(example.num.toFixed(2)); // 3.14

You can see that at runtime, example has keys named str and num, and the compiler is aware of this.


An enum is also an object with keys and values, so you can transform it the same way:

const LowercaseEnum = lowercaseKeys(OriginalEnum);
/* const LowercaseEnum: {
[x: number]: string;
readonly value_1: OriginalEnum.VALUE_1;
readonly value_2: OriginalEnum.VALUE_2;
} */
console.log(LowercaseEnum.value_1.toFixed()); // "0"
console.log(LowercaseEnum.value_2.toFixed()); // "1"

Hooray!


Well, that's great as far as it goes. But note that an enum also has some special features apart from a regular object. (See this answer for a more in-depth description of this differences.) For example, the name of an enum can also be used as a type corresponding to the union of its values:

interface Okay {
e: OriginalEnum;
}

But LowercaseEnum is just an object and was not declared as an enum; there is no type named LowercaseEnum:

interface Oops {
e: LowercaseEnum; // error
// ~~~~~~~~~~~~~
// 'LowercaseEnum' refers to a value,
// but is being used as a type here.
}

If you want such a type, you must make it:

type LowercaseEnum = OriginalEnum; // same values, so same type

Another difference is that a true numeric enum like OriginalEnum has a reverse mapping, where if OriginalEnum.VALUE_1 is 0, then OriginalEnum[0] is "VALUE_1":

console.log(OriginalEnum[0]); // "VALUE_1" as expected

But the transformed version doesn't have a useful reverse mapping, because only its keys have been changed; its values are untouched:

console.log(LowercaseEnum[0]); // still "VALUE_1", unexpected?

So, please be careful when using something like LowercaseEnum: while there are similarities, it's not a true enum.


Playground link to code

How to cast / assign one enum value to another enum

I made a working code from your question. You have missed the enum from your type definitions.

typedef enum EnumA
{
a_dog = 0,
a_cat = 1
} EnumA;

typedef enum EnumB
{
b_dog = 0,
b_cat = 1
} EnumB;

int main()
{
EnumA a = a_dog;
EnumB b;

b = (EnumB) a;
printf("%d\n", b);
return 0;
}

The code b = a also works properly without the cast. Also b = (int) a; is working - at least in C11, becuse enums are really just integers. Anyway, IMHO it is good practice to make an explicite cast.

Converting one Enum to another in JavaScript

TypeScript enums allow you to do a reverse mapping:

enum RowStates {
editing = 0,
sentToApproval,
approved
}

enum RowColors {
editing = '#ffffff',
sentToApproval = '#ffffcc',
approved = '#ccffb3'
}

function convert(rowState: RowStates) {
return RowColors[RowStates[rowState] as keyof typeof RowColors];
}

console.log(convert(RowStates.sentToApproval)); // prints '#ffffcc'

Set one kind of enum to another enum kind of enum in java

It would be better if you declare enum Type out of Entity or Response class. Then you could use same enum for both classes.

You can declare an enum at any of three levels:

  • Separate class
  • Nested within a class
  • Locally (in Java 16+)

For your situation, I suggest you use the first rather than the second.

C# - Convert one Enum to an other

SystemPersonTitles newValue = (SystemPersonTitles)(int)PersonTitle.Mr;

Out of the head, I cannot test this as I'm currently on my OSX.

How to convert one enum to another enum in java?

One way is to define a method asSimple() in your Detailed enum:

public enum Detailed {
PASSED {
@Override
Simple asSimple() {
return DONE;
}
},
INPROCESS {
@Override
Simple asSimple() {
return RUNNING;
}
},
ERROR1,
ERROR2,
ERROR3;
public Simple asSimple() {
return Simple.ERROR; // default mapping
}
}

You can then simply call the method when you want to do the mapping:

Detailed code = . . .
Simple simpleCode = code.asSimple();

It has the advantage of putting the knowledge of the mapping with the Detailed enum (where perhaps it belongs). It has the disadvantage of having knowledge of Simple mixed in with the code for Detailed. This may or may not be a bad thing, depending on your system architecture.

How to cast a value from one enum to another in Java?

You cannot cast from one enum to another, however each enum has guaranteed order, and you can easily translate one enum to another (preserving order). For example:

enum E1 {
ONE, TWO, THREE,
}

enum E2 {
ALPHA, BETA, GAMMA,
}

we can translate E1.TWO to/from E2.BETA by:

static E2 E1toE2(E1 value) {
return E2.values()[value.ordinal()];
}

static E1 E2toE1(E2 value) {
return E1.values()[value.ordinal()];
}


Related Topics



Leave a reply



Submit