Eya Eya - 3 months ago 12
C# Question

Methods inside enum in C#

In Java there is an option to write enum, and functions inside the enum object that can be used.

Is there such possibility in C# or is it just a string collection and that's it?

I tried to "override"

ToString()
function and it does not compile. Does someone have a simple code sample?

Answer

You can write extension methods for enum types:

enum Stuff
{
    Thing1,
    Thing2
}

static class StuffMethods
{

    public static String GetString(this Stuff s1)
    {
        switch (s1)
        {
            case Stuff.Thing1:
                return "Yeah!";
            case Stuff.Thing2:
                return "Okay!";
            default:
                return "What?!";
        }
    }
}

class Program
{


    static void Main(string[] args)
    {
        Stuff thing = Stuff.Thing1;
        String str = thing.GetString();
    }
}