views:

216

answers:

3

Hi. Is there a way I could point an Enum to another Enum? Here are the needs and details:

Currently:

  • I have a two public classes com.abcd.MyManager and com.abcd.data.MyObject.
  • MyObject class have pretty much everything is private except Types enum member.
  • MyManager class uses MyObject class
  • Notice MyObject class lives in a separate namespace.
  • One of the MyManager methods have following signature:
    public void Init(string name, MyObject.Types type)
    {
    // does Init
    }

Refactor requirement:

  • Just because of MyObject.Types used in the Init method and also it is living in another namespace. Developers have to include both namespaces in their code. I like to move the MyObject.Types enum to MyManager class. something similar like this:
    public void Init(string name, MyManager.Types type)
    {
    // does Init
    }

Any suggestions on how could I do this without breaking current structure? Thanks.

A: 

I don't see why moving the enumeration would break anything. You should be able to just move the enum to com.abcd.Types, and make sure the MyObject code file includes a using directive for the com.abcd namespace. If you really want to have the enum inside MyManager, then MyObject must refer to MyManager.Types instead of just Types.

Are there any specific problems you're running into when you attempt the refactoring?

Joren
+2  A: 

You can have one enum use the values from another, but you can't make them interchangeable (without casting).

public class MyManager
{
    public enum Types
    { 
        Type1 = com.abcd.data.MyObject.Types.Type1,
        Type2 = com.abcd.data.MyObject.Types.Type2,
        Type3 = com.abcd.data.MyObject.Types.Type3
    }
}

This will let you cast in between the two enums and get the same value for the same member names, but you'll still have to cast.

Adam Robinson
A: 

I have two suggestions.

1) Move the MyObject.Types enum to a separate project that both MyObject and MyManager has a reference to.

2)Create an enum in the MyManager project that matches the enum in the MyObject project. Then you can have some kind of mapping method:

public void Init(string name, MyManager.Types type)
{
   MyObject.Types t = type.ToMyObjectType();
}

internal static class Extensions
{
   public static MyObject.Types ToMyObjectType(this MyManager.Types t)
   {
      //do mapping
   }
}

I wouldn't suggest using the second approach, because if the enum in MyObject ever changes, you need to remember to update this code as well.

BFree