Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting Between Enums in C# [duplicate]

Possible Duplicate:
convert an enum to another type of enum

When casting between enums of different types, is it possibly to directly cast from one type to the other like so?

LicenseTypes type;
TypeOfLicense type2;

type2 = (TypeOfLicense)type;

Or is it necessary to cast the enum to an int first? The compiler doesn't complain, but I want to make sure I'm not going to get some kind of funky casting exception at runtime.

This may seem like an odd thing to do, but both enums are identical in structure and value. Only the type names differ in this case.

like image 728
Bender the Greatest Avatar asked Oct 04 '12 04:10

Bender the Greatest


1 Answers

Although its a duplicate and I have flagged it as well. You can do simple casting, beucase the underlying type is int, you can do:

LicenseTypes type = (LicenseTypes)TypeOfLicense.value3;

Here type will hold value '0';

Suppose you have:

public enum LicenseTypes 
{
    value1,
    value2,
}
public enum TypeOfLicense
{
    value3, 
    value4,
    value5
}

But if you try to Cast TypeOfLicence.value5 then the variable type will hold the int value 2

LicenseTypes type = (LicenseTypes)TypeOfLicense.value5;

You can also look at this link for creating extension methods for conversion between enums. (Its the accepted answer of the similar question)

like image 174
Habib Avatar answered Sep 29 '22 11:09

Habib