Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 387
Camilo Martin Avatar asked Oct 27 '10 05:10

Camilo Martin


People also ask

Can you add methods to enum?

You can use extension methods to add functionality specific to a particular enum type.

What is the main purpose of an extension method?

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.

Should you use extension methods?

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.

Can we extend enum in C#?

Answers. Yes, you can easily define a enumeration extending existing enum.


1 Answers

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.

like image 69
Marc Gravell Avatar answered Sep 21 '22 19:09

Marc Gravell