Extending yourself…

How many times have you found yourself doing this for enums:

public enum Role
{
  Guest,
  User,
  Privileged,
 
Administrator
}

public class RoleHelper
{
 
public static string GetName(Role role)
  
{
   
return Enum.GetName(typeof(Role), role);
 
}
}

Wouldn’t it be a lot nicer just to be able to go role.GetName()? As promised, I am now going to explain what Extension Methods are. Extensions Methods are a blessing 🙂 Basically, they allow you to add new methods to existing classes, so that the appear as if they were defined in the class. It’s almost as if you were adding the method inside of the class definition (though see the caveat below).

The syntax is pretty straight forward:

public static class RoleHelper
{
 
public static string GetName(this Enum e)
  {
   
return Enum.GetName(e.GetType(), e);
  }
}

Notice the “this” in front of the class name. That’s the secret sauce. The only other thing you need to remeber is that the methods must be declared inside public static classes.

So now, all your enum’s will have a handy GetName method which returns the name of the enum instead of having to write a helper method for each one!

Caveat: Even though it looks like you are just declaring another method for a class, you are not executing in the context of the class – this means you do not have access to the class’ private or protected members.

Advertisements
Post a comment or leave a trackback: Trackback URL.

Comments

  • Miles Thompson  On May 19, 2008 at 9:03 pm

    Extension methods are indeed neat. And this is a clear example, but in this case I think overkill.

    With .Net 3.5 compilation enabled, and this extension method defined, one can get the string valued ‘name’ of an enum, thus..

    role.GetName();

    On the other hand back in 2.0 world we managed to get by with..

    role.ToString();

    Which I think you’ll find produces the exact same output.

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: