C # - convert one Enum to another

I have 2 listings

public enum PersonTitle{ Mr=0,Ms=1,Mrs=2 } public enum SystemPersonTitles{ Mr=0,Ms=1,Mrs=2 } 

How do I convert one of the others (without switching cases or If Statement) .

 public void SystemPersonTitles TellWhatYouAre(PersonTitle personTitle){ //here } //usage SystemPersonTitles systemPersonTitles = TellWhatYouAre(PersonTitle.Ms); 
+7
source share
8 answers
 SystemPersonTitles newValue = (SystemPersonTitles)(int)PersonTitle.Mr; 

Out of my head, I cannot verify this, as I am currently in OSX.

+10
source

Enumerations are simply distinguished integers, so you can simply translate from one to another:

 public SystemPersonTitles TellWhatYouAre(PersonTitle personTitle) { return (SystemPersonTitles)personTitle; } 

Note that this conversion is based on int values, not on names.

+8
source

Send it to int and then back to another Enum.

 public void SystemPersonTitles TellWhatYouAre(PersonTitle personTitle){ int value = (int)personTitle; var systemPersonTitle = (SystemPersonTitles)value; } 

It can also be done directly, as others point out, but I wanted to be explicit in order to show the mechanics behind the decision .

 SystemPersonTitles systemPersonTitle = (SystemPersonTitles)personTitle; 
+3
source

Since both of them are mostly int, you can just drop it.

So, if you have an instance of PersonTitle called title , you can do this:

 SystemPersonTitles newTitle = (SystemPersonTitles)title; 
+3
source

If you want to convert them by value, you can use this:

 (SystemPersonTitles)PersonTitle.Mr; 

If you want to convert them by name, you can use this:

 public bool TryConvertToSystemPersonTitles( PersonTitle personTitle, out SystemPersonTitles result) { return Enum.TryParse(personTitle.ToString(), out result); } 
+2
source

You can do it:

 PersonTitle person = PersonTitle.Mr; SystemPersonTitles system = (int) person; 

This will do the conversion according to the int value.

If you want to do this by name, follow these steps:

 PersonTitle person = PersonTitle.Mr; SystemPersonTitles sys = (SystemPersonTitles)Enum.Parse(person.GetType(), person.ToString()); 
+1
source

There is no direct way to do this, and that is the right way. let's say you could do:

 personTitle = systemPersonTitle; 

what will happen to your code if SystemPersonTitles changes to any of them:

 public enum SystemPersonTitles1{ Mr=1,Ms=2,Mrs=3 } public enum SystemPersonTitles2{ Mr=0,Ms=1,Mrs=2,UnKnown=3 } public enum SystemPersonTitles3{ Mrs=0,Ms=1,Mr=2 } 

Or any other changes you might think of.
you can get around this limitation, but it's just bad programming. If you decide to use the value "int" and lose the ability to enumerate. just use "int" to start ...

+1
source

Something like (SystemPersonTitles) (int) personTitle

0
source

All Articles