Enums in .NET– part V

As we’ve seen, we’re limited quite limited when you need to define a new enumerated type: we can only specify the enum base type, the symbolic names and its associated values. That means that you can’t add new instance methods to an enum (which doesn’t really make sense because, as we’ve seen, enums are mapped into structs by the compiler). Fortunately, from C# 4.0 onwards there’s a workaround: we can rely on extension methods for adding methods that are supposed to be used as instance methods.

To  show you how we can improve  our code with utility extension methods, we’ll start by creating a new flags enums (in fact, we’ll simple reuse the Permissions flag enums we’ve introduced in a previous post):

[Flags]
public enum Permissions {
    Write = 1,  //001
    Read = 2,   //010
    Special = 4 //100
}

In these cases, it would be really helpful to have a method for checking if a specific bit is on or off. Here’s how we might check that:

public static class PermissionsExtensions {
    public static Boolean IsBitOn(this Permissions perm, Permissions permissionToCheck) {
        return ( perm & permissionToCheck ) == permissionToCheck;
    }
}

And now, we can perform our test as if we’ve added IsBitOn directly to the Enum declaration:

var perm = Permissions.Write | Permissions.Read;
Console.WriteLine(perm.IsBitOn(Permissions.Read));//true

Simple and it works! And now, I’ll leave it to you to think of some cool work which can be done with extension methods Winking smile Stay tuned for more!

Advertisements

~ by Luis Abreu on June 12, 2011.

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: