My question is best illustrated with an example.
Suppose I have the enum:
public enum ArrowDirection
{
North,
South,
East,
West
}
I want to associate the unit vector corresponding to each direction with that direction. For example I want something that will return (0, 1) for North, (-1, 0) for West, etc. I know in Java you could declare a method inside the enum which could provide that functionality.
My current solution is to have a static method — inside the class that defines the enum — that returns a vector corresponding to the passed in ArrowDirection (the method uses a HashTable to accomplish the lookup but that’s not really important). This seems… unclean.
Question:
Is there a best-practice solution for storing additional information corresponding to an enum in .NET?
There’s a FANTASTIC new way to do this in C# 3.0. The key is this beautiful fact: Enums can have extension methods! So, here’s what you can do:
Now, you can do this:
Sweet! I only found this out about a month ago, but it is a very nice consequence of the new C# 3.0 features.
Here’s another example on my blog.