183

In Java, it's possible to have methods inside an enum.

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

I tried to override ToString() but it does not compile. Does someone have a simple code sample?

Matthias Braun
  • 24,493
  • 16
  • 114
  • 144
Eya
  • 1,843
  • 2
  • 11
  • 5
  • I don't think you can have methods inside an Enum in C#. What are you trying to do? – Duncan Howe May 12 '11 at 23:27
  • trying to get Java behavior and encapsulate close logic to Enums. anyway I see from the answers it is not possible - I'll implement extensions. – Eya May 13 '11 at 09:00

6 Answers6

303

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();
    }
}
MarkPflug
  • 25,238
  • 6
  • 40
  • 48
20

You can write an extension method for your enum:

How to: Create a New Method for an Enumeration (C# Programming Guide)

Jay Riggs
  • 51,115
  • 9
  • 133
  • 146
13

Another option is to use the Enumeration Class created by Jimmy Bogard.

Basically, you must create a class that inherits from his Enumeration. Example:

public class EmployeeType : Enumeration
{
    public static readonly EmployeeType Manager 
        = new EmployeeType(0, "Manager");
    public static readonly EmployeeType Servant 
        = new EmployeeType(1, "Servant");
    public static readonly EmployeeType Assistant
        = new EmployeeType(2, "Assistant to the Regional Manager");

    private EmployeeType() { }
    private EmployeeType(int value, string displayName) : base(value, displayName) { }

    // Your method...
    public override string ToString()
    {
        return $"{value} - {displayName}!";
    }
}

Then you can use it like an enum, with the possibility to put methods inside it (among another things):

EmployeeType.Manager.ToString();
//0 - Manager
EmployeeType.Servant.ToString();
//1 - Servant
EmployeeType.Assistant.ToString();
//2 - Assistant to the Regional Manager

You can download it with NuGet.

Although this implementation is not native in the language, the syntax (construction and usage) is pretty close to languages that implement enums natively better than C# (Kotlin for example).

fabriciorissetto
  • 8,005
  • 4
  • 58
  • 69
3

Nope. You can create a class, then add a bunch of properties to the class to somewhat emulate an enum, but thats not really the same thing.

class MyClass
{
    public string MyString1 { get{ return "one";} }
    public string MyString2 { get{ return "two";} }
    public string MyString3 { get{ return "three";} }

    public void MyMethod()
    {
        // do something.
    }
}

A better pattern would be to put your methods in a class separate from your emum.

Kyle Trauberman
  • 24,648
  • 13
  • 83
  • 116
  • An extension of this is actually a good practice: instead of properties returning strings, you can return an instance of MyClass that stores a text value inside it. Practically this would be equivalent to Java's enums. It is suggested that enum classes - such as your suggestion with some tweaks - are preferred to the C# enum type. – TheAgent Apr 03 '21 at 11:21
1

Since I came across, and needed the exact opposite of enum to string, here is a Generic solution:

static class EnumExtensions {
    public static T GetEnum<T>(this string itemName) {
        return (T) Enum.Parse(typeof(T), itemName, true);
    }
}

This also ignores case and is very handy for parsing REST-Response to your enum to obtain more type safety. Hopefully it helps someone

scrat84
  • 185
  • 1
  • 8
-13

C# Does not allow use of methods in enumerators as it is not a class based principle, but rather an 2 dimensional array with a string and value.

Use of classes is highly discouraged by Microsoft in this case, use (data)struct(ures) instead; The STRUCT is intended as a light class for data and its handlers and can handle functions just fine. C# and its compiler don't have the tracking and efficiency capabilities as one knows from JAVA, where the more times a certain class / method is used the faster it runs and its use becomes 'anticipated'. C# simply doesn't have that, so to differentiate, use STRUCT instead of CLASS.

user236800
  • 107
  • 1
  • 9
    Seven down votes without a single comment to explain what's supposed to be wrong with this answer? C'mon guys... – Good Night Nerd Pride Apr 25 '16 at 11:49
  • Is the all the information provided in this post wrong? – V K Aug 09 '16 at 13:20
  • 7
    This part is true: C# Does not allow use of methods in enumerators. I'm not sure if the reasoning is correct though, and the second paragraph seems completely irrelevant to the question. If there's a way to use a struct to simulate an enum with behaviour, providing an example would be best. – Mishelle Nov 01 '16 at 16:24
  • 3
    I think the implications are fairly clear here. Do not replace an enum (which is a value type) with a class (which is a reference type) just to add methods, since structs also can have methods and are also value types. – smelch Mar 29 '17 at 00:21