Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set one enum equal to another

Tags:

c#

.net

enums

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

like image 570
BoundForGlory Avatar asked Dec 04 '22 16:12

BoundForGlory


2 Answers

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

obj1.enum1 = (MVC1.MyEnum)((int)obj2.enum1);
like image 195
Chris Sinclair Avatar answered Dec 10 '22 09:12

Chris Sinclair


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.

like image 35
lesderid Avatar answered Dec 10 '22 10:12

lesderid