c# Get all enum values greater than a given value?

Probably depending on version of .NET. But this works very well for me:

There is no need to convert or to use special tricks. Just compare with the usual operators:

using System;

enum Test { a1, a2, a3, a4 }

class Program
{
    static void Main(string[] args)
    {
        Test a = Test.a2;

        Console.WriteLine((a > Test.a1));
        Console.WriteLine((a > Test.a2));
        Console.WriteLine((a > Test.a3));
        Console.WriteLine((a > Test.a4));

        Console.ReadKey();
    }
}

Output:

True
False
False
False

You can use the following helper method to give you a set of roles allowed for a given role:

    private IEnumerable<RoleName> AllAllowedRoles(RoleName level)
    {
        return Enum.GetValues(typeof(RoleName)).Cast<RoleName>().Where(role => level >= role);
    } 

And then assign all of them to the user.


in order to have a better definition of which role is greater than the other you need to assign numeric values to your roles like this:

public enum RoleName
{
    RegisteredUser = 2,
    Moderator = 4,
    Administrator = 8,
    Owner = 16
}

Now if you cast any instance of type RoleName to (int) you will get the numeric value and therefore you will be able to compare them against each other.

Note:
1. Here I use powers of 2 as values to allow combining RoleNames using bit-wise operators.

Tags:

C#

Enums