Jun 12

Enums in .NET– part V

Posted in .NET Basics C#      Comments Off on 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):

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;

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!