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?
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?
You can write extension methods for enum types:
Another option is to use the Enumeration Class created by Jimmy Bogard.
Basically, you must create a class that inherits from his
Enumeration
. Example:Then you can use it like an enum, with the possibility to put methods inside it (among another things):
You can download it with NuGet.
You can write an extension method for your enum:
How to: Create a New Method for an Enumeration (C# Programming Guide)
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.
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.
A better pattern would be to put your methods in a class separate from your emum.