I have a Direction Enum:
Public Enum Direction
Left
Right
Top
Bottom
End Enum
And Sometimes I need to get the inverse, so it seems nice to write:
SomeDirection.Inverse()
But I can't put a method on an enum! However, I can add an Extension Method (VS2008+) to it.
In VB, Extension Methods must be inside Modules. I really don't like modules that much, and I'm trying to write a (moderately) simple class that I can share in a single file to be plugged into other projects.
Modules can only reside in the file/namespace level so I have one in the bottom of the file now:
Public Class MyClass
'...'
End Class
Public Module Extensions
<Extension()> _
Public Function Inverse(ByVal dir As Direction) As Direction
'...'
End Function
End Module
It works, and "if it ain't broke, don't fix it", but I'd love to know if I'm doing it wrong and there's a better way with less boilerplate. Maybe in .NET 4?
Finally, I know I could write a structure that behaves like an enum, but that seems even more backwards.
You can use extension methods to add functionality specific to a particular enum type.
Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type.
Extension methods are an excellent addition to the C# language. They enable us to write nicer, more readable code. They allow for more functionally styled programming, which is very much needed in an object-oriented language. They also should be used with care.
Answers. Yes, you can easily define a enumeration extending existing enum.
That is indeed the only way to add (the appearance of) a method to an enum.
Note that in C# the extension method would be defined on a static class, but that is a trivial difference, largely one of nomenclature.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With