BoundForGlory
BoundForGlory

Reputation: 4427

Set one enum equal to another

I have 2 enums in 2 different objects. I want to set the enum in object #1 equal to the enum in object #2.

Here are my objects:

namespace MVC1 {

    public enum MyEnum {
        firstName,
        lastName
      }

   public class Obj1{
        public MyEnum enum1;
    }
   }


     namespace MVC2 {

    public enum MyEnum {
        firstName,
        lastName
      }

    public class Obj2{
        public MyEnum enum1;
      }
    }

I want to do this, but this wont compile:

 MVC1.Obj1 obj1 = new MVC1.Obj1();
 MVC2.Obj2 obj2 = new MVC2.Obj2();
 obj1.enum1 = obj2.enum1; //I know this won't work.

How do I set the enum in Obj1 equal to the enum in Obj2? Thanks

Upvotes: 5

Views: 7037

Answers (3)

lesderid
lesderid

Reputation: 3430

Enums have an underlying integer type, which is int (System.Int32) by default, but you can explicitly specify it too, by using "enum MyEnum : type".

Because you're working in two different namespaces, the Enum types are essentially different, but because their underlying type is the same, you can just cast them:

obj1.enum1 = (MVC1.MyEnum) obj2.enum1;

A note: In C# you have to use parentheses for function calls, even when there aren't any parameters. You should add them to the constructor calls.

Upvotes: 7

Pranay Rana
Pranay Rana

Reputation: 176956

Best way to do it is check if it's in range using Enum.IsDefined:

int one = (int)obj2.enum1;
if (Enum.IsDefined(typeof(MVC1.MyEnum), one )) { 
  obj1.enum1 = (MVC1.MyEnum)one;
}

 obj1.enum1 = (MVC1.MyEnum) Enum.Parse(typeof(MVC1.MyEnum),
                                 ((int)obj2.enum1).ToString());

or

int one = (int)obj2.enum1;  
obj1.enum1 = (MVC1.MyEnum)one; 

Upvotes: 2

Chris Sinclair
Chris Sinclair

Reputation: 23218

Assuming that you keep them the same, you can cast to/from int:

obj1.enum1 = (MVC1.MyEnum)((int)obj2.enum1);

Upvotes: 7

Related Questions