How do I overload an operator for an enumeration in C#?

ChrisHDog picture ChrisHDog · Aug 31, 2009 · Viewed 26.7k times · Source

I have an enumerated type that I would like to define the >, <, >=, and <= operators for. I know that these operators are implictly created on the basis of the enumerated type (as per the documentation) but I would like to explictly define these operators (for clarity, for control, to know how to do it, etc...)

I was hoping I could do something like:

public enum SizeType
{
    Small = 0,
    Medium = 1,
    Large = 2,
    ExtraLarge = 3
}

public SizeType operator >(SizeType x, SizeType y)
{

}

But this doesn't seem to work ("unexpected token") ... is this possible? It seems like it should be since there are implictly defined operators. Any suggestions?

Answer

Mehrdad Afshari picture Mehrdad Afshari · Aug 31, 2009

You can't do that. You can only provide overloaded operators for classes and structs you define -- and at least one of the parameters should be of type of the class or struct itself. That is, you can declare an overloaded addition operator that adds a MyClass to MyEnum but you can never do that with two MyEnum values.