65.9K
CodeProject is changing. Read more.
Home

Passing Enum type as a parameter

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.50/5 (4 votes)

Aug 23, 2011

CPOL

1 min read

viewsIcon

100481

Cycling through (looping around) enum lists.

In a regular method call, we cannot pass a Type as a function parameter and to be honest, my need to do this has been quite rare. However, it just so happened that the other day I needed to do just this.

In my application, I wanted the user to be able to select next or previous to iterate through a list. When we get to the end of a sequence, I want to loop around by going to the other end of the sequence.

So no big deal here until I decided that I wanted to continue to use my already established enums regardless of their underlying type. But the thing about an Enum is that it is a Type, which presented the first problem. How do I send the message about the enum I want to iterate through to a method?

Well, turns out, this is a perfect job for a generic method. With a generic method, I can send a Type as a parameter.

GetNextEnum<T> and GetPreviousEnum<T> are generic functions that can be used to cycle through any enum list of any type. In my case, the user selects “Next” or “Previous” for cycling through the CameraActionModes. The CameraActionMode are defined as an enum. I also had the same type of action needed for the MouseMode enum. Reuse baby! It is a good thing.

private void SelectNextCameraMode()
{
    World.Camera.CameraMode = 
     (CameraActionMode)GetNextEnum<cameraactionmode>(World.Camera.CameraMode);
    UpdateCameraModeLabel();
}

private void SelectNextMouseMode()
{
    this.mouseMode = (MouseMode)GetNextEnum<mousemode>(this.mouseMode);
    UpdateMouseModeLabel();
}

private Enum GetNextEnum<t>(object currentlySelectedEnum)
{
    Type enumList = typeof(T);
    if (!enumList.IsEnum)
        throw new InvalidOperationException("Object is not an Enum.");

    Array enums = Enum.GetValues(enumList);
    int index = Array.IndexOf(enums, currentlySelectedEnum);
    index = (index + 1) % enums.Length;
    return (Enum)enums.GetValue(index);
}

private Enum GetPreviousEnum<t>(object currentlySelectedEnum)
{
    Type enumList = typeof(T);
    if (!enumList.IsEnum)
        throw new InvalidOperationException("Object is not an Enum.");

    Array enums = Enum.GetValues(enumList);
    int index = Array.IndexOf(enums, currentlySelectedEnum);
    index = (((index == 0) ? enums.Length : index) - 1);
    return (Enum)enums.GetValue(index);
}