Is an Extension Method the only way to add a function to an Enum?

.net, boilerplate, enums, extension-methods, vb.net

Solution

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.

Problem

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.

Original source