Extending Enums

2 11 2012

Not really going to be a long post since I’m up to my ears in code and the tests aren’t going to write themselves (now THAT would be a worthy plugin for my IDE).

Enumerations, some people like them and some people think they’re evil. Like everything else I say they’re a tool that can be used and/or abused. I like to capture semantic meaning of certain unshakable facts, usually in regards to certain values that are used as flags, by cementing them as enumerated values. This post isn’t much about the reasons to use or not to use enums but rather a convenient feature of C# to allow us to supply extension methods for enumerated types as well given that enums, like EVERYTHING else in C# are derived from object.

Extension methods, just as a quick aside, are also a neat feature of C# that can be abused quite sorely 😛 and they, basically, allow programmers to ‘extend’ an object operational field (ie. interface). And it goes something like this:

// This is our enum
public enum Flags
{
  Flag1,
  Flag2,
}

// Contains our extension methods; notice must be static.
public static class FlagsExtensions
{
  // An extension method; notice accepts the 'this' pointer.
  public static string GetString(this Flags flag)
  {
    return "Hello";
  }
}

And that’s all folks, we can now get a nicely formatted string out from our flags.

string flagString = Flags.Flag1.GetString()

Perhaps not the most useful thing in the world but nice to know anyway and it helped me a little bit in the last couple of days 😀

“And they say the ghost of Lucius Clay gets up and he walks around.”

Advertisements

Actions

Information

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: