JohnT
JohnT

Reputation: 77

Alias for enum value name in C#

Can I make an alias for enum value name in C# ? For example I have two files: A and B.

public class A
{
    public enum myEnum 
        {
            value_1,
            value_2 
        };
}

And I want to use this enum in B class:

public class B
{
 private A.myEnum[] tab = { A.myEnum.value_1, A.myEnum.value_2,  A.myEnum.value_1 ..}

}

I want to make an alias for: A.myEnum.value_1 and A.myEnum.value_2 so I could write

private A.myEnum[] tab = { alias_1, alias_2},

Upvotes: 3

Views: 3139

Answers (3)

t3chb0t
t3chb0t

Reputation: 18675

You just could get all the values and turn them into an array:

myEnum[] tab = Enum.GetValues(typeof(myEnum)).Cast<myEnum>().ToArray();

Upvotes: 0

Rahul
Rahul

Reputation: 77876

Using a helper method like

public static myEnum GetEnumName(string str)
{
    switch(str)
    {
        case "alias_1": return myEnum.Value_1;
        case "alias_2": return myEnum.Value_2;
        default: throw new Exception();
    }
}

Upvotes: 0

Matthew Watson
Matthew Watson

Reputation: 109567

I think I might be missing something, but:

public class B
{
    private const A.myEnum alias_1 = A.myEnum.value_1;
    private const A.myEnum alias_2 = A.myEnum.value_2;

    private A.myEnum[] tab = {alias_1, alias_2};
}

Upvotes: 3

Related Questions