Search code examples
c#convention

Nested Enum Style and Convention


I have an enum that controls the way a class operates. This enum is only applicable to the class, and as a result feels like it should be nested. However, that class needs an instance of the enum as a member, which ideally would be named identically to the enum. Of course, this is not possible.

My primary concern is providing a clean and clear API. The two options I see are:

Nest the enum and name either the instance member or the enum itself something that is 'less than perfect'

Put the enum outside the class, which kind of sort of but not really pollutes the namespace, and may reduce discover-ability. (Writing this now, it strikes me that discover-ability is likely not a concern, since there is a single usage point, a property).

Is there an accepted convention for cases such as this? Here's a snippet illustrating the use case:

public class MultiModeActionFacadeObject : IAction
{
    public enum ActionMode // enum only applies to this class
    { 
        Fast,
        Accurate,
        Intermediate
    }

    private readonly IAction _accurate, _fast, _intermediate;

    internal MultiModeActionFacadeObject(IAction fastAction, IAction accurateAction, IAction intermediateAction)
    {
        _fast = fastAction;
        _accurate = accurateAction;
        _intermediate = intermediateAction;

    }

    // preference would be to call this member ActionMode, but obviously members can't share names
    // although I believe this could be accomodated, outside of static members, by some changes to 
    // qualification requirements. That's not the concern here though.
    public ActionMode Mode { get; set; } 

    public void DoWork(object onThis)
    {
        switch (Mode)
        {
            case ActionMode.Fast:
                _fast.DoWork(onThis);
                break;
            case ActionMode.Accurate:
                _accurate.DoWork(onThis);
                break;
            case ActionMode.Intermediate:
                _intermediate.DoWork(onThis);
                break;
        }
    }
}

Solution

  • It seems much more common to place the enum outside the class. Keeping it inside means you will end up needing to specify ClassName.Enum everytime you set the mode:

    var mma = new MultiModeActionFacadeObject(fastAction, accurateAction, intermediateAction)
                {
                    Mode = 
                        MultiModeActionFacadeObject.ActionMode.Accurate
                };
    

    Also, since either way is valid, I don't consider this a definitive "answer". I would have just added a comment on your original question, but that requires 50+ rep :)