Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Min and Max operations on enum values

Tags:

c#

Using C#, how can I take the min or max of two enum values?

For example, if I have

enum Permissions
{
    None,
    Read,
    Write,
    Full
}

is there a method that lets me do Helper.Max(Permissions.Read, Permissions.Full) and get Permissions.Full, for example?

like image 873
Timothy Shields Avatar asked Apr 10 '13 18:04

Timothy Shields


People also ask

Is there a limit on enums?

An ENUM column can have a maximum of 65,535 distinct elements.

Can an enum have two values?

The Enum constructor can accept multiple values.

What is the correct usage of enum?

Enumeration or Enum in C is a special kind of data type defined by the user. It consists of constant integrals or integers that are given names by a user. The use of enum in C to name the integer values makes the entire program easy to learn, understand, and maintain by the same or even different programmer.


1 Answers

Enums implement IComparable so you can use:

public static T Min<T>(T a, T b) where T : IComparable
{
    return a.CompareTo(b) <= 0 ? a : b;
}
like image 58
Lee Avatar answered Sep 22 '22 22:09

Lee