Alex Rivera | Logout

C#: Is there a way to classify enums?

Asked 2010-01-21T14:37:27.317
13

Given the following enum:

    public enum Position
    {
        Quarterback,
        Runningback,
        DefensiveEnd,
        Linebacker
    };

Is it possible to classify the named constants, such that I could mark 'Quarterback' and 'Runningback' as offensive positions and 'DefensiveEnd' and 'Linebacker' as defensive positions?

Edit
Report

2 Answers

24

You can use attributes:

public enum Position
{
    [OffensivePosition]
    Quarterback,
    [OffensivePosition]
    Runningback,
    [DefensivePosition]
    DefensiveEnd,
    [DefensivePosition]
    Linebacker
};

And then check for IsDefined on an appropriate FieldInfo. Syntax is not very pretty, but you can throw in a couple of extension methods to make things more manageble:

public static bool IsOffensivePosition(PositionType pt)
{
    return typeof(PositionType).GetField(Enum.GetName(typeof(PositionType), pt)).
        IsDefined(typeof(OffensivePositionAttribute), false);
}
answered 2010-01-21T14:39:32.127
0

You can declare the enums in a class:

public class Position
{
    public enum Offensive { Quarterback = 1, RunningBack }
    public enum Defensive { DefensiveEnd = 10, LineBacker }
}

Note that the Defensive values start at 10 so that values don't overlap. You don't state why you want to do this, so this might not meet your needs.

answered 2010-01-21T14:57:13.587

Your Answer