Search code examples
c#.netstaticenums

Why can't we add static methods to enums?


I wonder why we can't add static methods (only methods, not properties) into enums? Is there any explanation for that?

It would be very useful if it was allowed.

And I also want to learn who forbids us to do it? Is it IL or C#?

Edit:

I don't want to use extension methods. Because I dont need to pass an instance of that enum. I don't need it's value there...

I want to call something like FooTypes.GetGoodFoos() not something FooTypes.BadFoo.GetSomething()

Edit 2:

Is that only me who thinks this could be more useful rather than writing this method in another class?

public enum Colors
{
    Red,
    LightRed,
    Pink,
    /* .
       .
       . */
    Green

    public static Colors[] GetRedLikes()
    {
        return new Colors[]
        {
            Colors.Red,
            Colors.LightRed,
            Colors.Pink
        }
    }
}

Solution

  • We can't add methods to enums because is how the language is made, and you are free to read the specification of the C# Language Specification

    14.3 Enum members

    The body of an enum type declaration defines zero or more enum members, which are the named constants of the enum type. No two enum members can have the same name.

    enum-member-declarations: enum-member-declaration enum-member-declarations , enum-member-declaration enum-member-declaration: attributesopt identifier attributesopt
    identifier = constant-expression

    Each enum member has an associated constant value. The type of this value is the underlying type for the containing enum. The constant value for each enum member must be in the range of the underlying type for the enum.