Sha Le
Sha Le

Reputation: 3

C# Enum pointing to another Enum (refactoring)

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

Currently:

Refactor requirement:

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

Upvotes: 0

Views: 1189

Answers (3)

BFree
BFree

Reputation: 103740

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.

Upvotes: 0

Adam Robinson
Adam Robinson

Reputation: 185643

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.

Upvotes: 3

Joren
Joren

Reputation: 14746

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?

Upvotes: 0

Related Questions