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.