180

I have this Enum code:

enum Duration { Day, Week, Month };

Can I add a extension methods for this Enum?

8
  • 1
    Have you seen this?stackoverflow.com/questions/2422113/…
    – badpanda
    Commented Mar 13, 2013 at 14:27
  • 1
    Also, this. stackoverflow.com/questions/276585/…
    – badpanda
    Commented Mar 13, 2013 at 14:30
  • short answer, yes. In this specific case you might want to consider the use of TimeSpan
    – Jodrell
    Commented Mar 13, 2013 at 14:31
  • 2
    Using extension methods on an enum would make me feel dirty. Create a class to encapsulate what is needed. Keep an enum as simple as possible. If you need more logic associated with it, then create a Duration class that exposes day, week, month plus contains any other logic that would have been in the extension method. Commented Mar 13, 2013 at 14:31
  • 3
    I like having enum extension methods for flag groups. I prefer in if clauses for instance Day.IsWorkday() over (Day & Days.Workday) > 0 with Days.Workday defined as Monday | Tuesday ... | Friday. The former is more clear in my opinion and has exactly the latter implemented. Commented Jul 11, 2018 at 7:42

8 Answers 8

160

According to this site:

Extension methods provide a way to write methods for existing classes in a way other people on your team might actually discover and use. Given that enums are classes like any other it shouldn’t be too surprising that you can extend them, like:

enum Duration { Day, Week, Month };

static class DurationExtensions 
{
  public static DateTime From(this Duration duration, DateTime dateTime) 
  {
    switch (duration) 
    {
      case Day:   return dateTime.AddDays(1);
      case Week:  return dateTime.AddDays(7);
      case Month: return dateTime.AddMonths(1);
      default:    throw new ArgumentOutOfRangeException("duration");
    }
  }
}

I think enums are not the best choice in general but at least this lets you centralize some of the switch/if handling and abstract them away a bit until you can do something better. Remember to check the values are in range too.

You can read more here at Microsft MSDN.

7
  • 1
    Enums in C# kind of suck because this compiles and runs: Duration d = 0;
    – GHP
    Commented Mar 30, 2016 at 15:32
  • 37
    Given that enums are classes no they aren't classes.
    – wingerse
    Commented Sep 2, 2017 at 18:17
  • 3
    I use this sort of extension only if it is about the enum directly, like days of the week and extension methods IsWeekday(), IsWeekendday(). But classes are meant to encapsulate behaviours, so if there are a lot or complicated behaviours to encapsulate, a class is probably better. If it's limited and basic, I personally find extensions on enums okay. As with most design decisions there are fuzzy boundaries between choices (IMO). It's worth noting that extensions can only be done on top level static classes, not nested classes. If your enum is part of a class you'll need to make a class.
    – FreeText
    Commented Oct 22, 2019 at 14:45
  • 9
    @WingerSendon if you F12 on Enum (not enum) in VS2019, it takes you to metadata which includes public abstract class Enum : ValueType, IComparable, ... - so it looks like a class to me, since I think enum and Enum are synonyms. Commented Nov 17, 2020 at 22:07
  • 1
    @wingerse well, not as C# construct, but the underlying IL is pretty much the same between an enum and a static class with constant fields named like the enum values. In the context of this question this does not help, but thought it might be an interesting fun fact.
    – Ardor
    Commented Jul 19, 2022 at 13:04
94

You can also add an extension method to the Enum type rather than an instance of the Enum:

/// <summary> Enum Extension Methods </summary>
/// <typeparam name="T"> type of Enum </typeparam>
public class Enum<T> where T : struct, IConvertible
{
    public static int Count
    {
        get
        {
            if (!typeof(T).IsEnum)
                throw new ArgumentException("T must be an enumerated type");

            return Enum.GetNames(typeof(T)).Length;
        }
    }
}

You can invoke the extension method above by doing:

var result = Enum<Duration>.Count;

It's not a true extension method. It only works because Enum<> is a different type than System.Enum.

3
  • 1
    Can the class be static to ensure all its methods behave like extensions? Commented Feb 4, 2018 at 1:40
  • 31
    For future readers: the name ambiguity of Enum<T> is a bit confusing. The class could also be called EnumUtils<T> and the method call would resolve to EnumUtils<Duration>.Count.
    – Namoshek
    Commented Feb 27, 2019 at 8:02
  • 12
    As of C# 7.3 instead of where T : struct, IConvertible you can actually use where T : System.Enum (and then also remove the ArgumentException, I guess)
    – Tobias Xy
    Commented Oct 19, 2020 at 13:06
70

Of course you can, say for example, you want to use the DescriptionAttribue on your enum values:

using System.ComponentModel;

public enum Duration 
{ 
    [Description("Eight hours")]
    Day,

    [Description("Five days")]
    Week,

    [Description("Twenty-one days")] 
    Month 
}

Now you want to be able to do something like:

Duration duration = Duration.Week;
var description = duration.GetDescription(); // will return "Five days"

Your extension method GetDescription() can be written as follows:

using System.ComponentModel;
using System.Reflection;

public static string GetDescription(this Enum value)
{
    FieldInfo fieldInfo = value.GetType().GetField(value.ToString());
    if (fieldInfo == null) return null;
    var attribute = (DescriptionAttribute)fieldInfo.GetCustomAttribute(typeof(DescriptionAttribute));
    return attribute.Description;
}
4
  • i was looking to create a extension to almost exactly what you sample did, except my use DisplayAttribute Localized GetDescription. cheers
    – George
    Commented Dec 29, 2017 at 13:41
  • This is a nice alternative, though I think the namespace is just System.ComponentModel?
    – TomDestry
    Commented Dec 29, 2018 at 16:39
  • 1
    Nice perspective and thank you for showing the implementation as well as the extension code. To pile on: with your implementation, you can also call it like this: var description = Duration.Week.GetDescription(); Commented Jun 1, 2020 at 16:01
  • OK, the method GetDescription() that you wrote would work for some other enum too, but I wonder can it be simplified if you declare it with (this Duration value) instead of (this Enum value) and then you know that you work on Duration type specificaly? Commented Sep 3, 2022 at 5:41
50

All answers are great, but they are talking about adding extension method to a specific type of enum.

What if you want to add a method to all enums like returning an int of current value instead of explicit casting?

public static class EnumExtensions
{
    public static int ToInt<T>(this T soure) where T : IConvertible//enum
    {
        if (!typeof(T).IsEnum)
            throw new ArgumentException("T must be an enumerated type");

        return (int) (IConvertible) soure;
    }

    //ShawnFeatherly funtion (above answer) but as extention method
    public static int Count<T>(this T soure) where T : IConvertible//enum
    {
        if (!typeof(T).IsEnum)
            throw new ArgumentException("T must be an enumerated type");

        return Enum.GetNames(typeof(T)).Length;
    }
}

The trick behind IConvertible is its Inheritance Hierarchy see MDSN

Thanks to ShawnFeatherly for his answer

3
  • 2
    the best answer! Commented Jun 8, 2017 at 1:26
  • Ditto. It works if I call the extension directly (e.g. MyExtention.DoThing(myvalue)) but doesn't actually attach to the enum (e.g. myvalue.DoThing()) Commented Jul 5, 2019 at 16:56
  • 4
    FYI, C# 7.3 now supports Enum as a generic type constraint Commented Jul 15, 2019 at 18:50
11

A Simple workaround.

public static class EnumExtensions
{
    public static int ToInt(this Enum payLoad) {

        return ( int ) ( IConvertible ) payLoad;

    }
}

int num = YourEnum.AItem.ToInt();
Console.WriteLine("num : ", num);
8

You can create an extension for anything, even object(although that's not considered best-practice). Understand an extension method just as a public static method. You can use whatever parameter-type you like on methods.

public static class DurationExtensions
{
  public static int CalculateDistanceBetween(this Duration first, Duration last)
  {
    //Do something here
  }
}
0
6

See MSDN.

public static class Extensions
{
  public static string SomeMethod(this Duration enumValue)
  {
    //Do something here
    return enumValue.ToString("D"); 
  }
}
3
  • 7
    A void return value on an enum is kind of weird. I'd think about a more realistic sample. Commented Mar 13, 2013 at 14:41
  • 4
    @psubsee2003 the OP surely has enough knowledge to change this to suit his needs? Why does the sample matter, it's enough to answer the initial question. Commented Mar 13, 2013 at 14:46
  • 3
    Am I the only one who finds the code examples on MSDN weird? Most of the time you need some real effort to understand what they're trying to do!
    – Stacked
    Commented Sep 23, 2016 at 7:26
1

we have just made an enum extension for c# https://github.com/simonmau/enum_ext

It's just a implementation for the typesafeenum, but it works great so we made a package to share - have fun with it

public sealed class Weekday : TypeSafeNameEnum<Weekday, int>
{
    public static readonly Weekday Monday = new Weekday(1, "--Monday--");
    public static readonly Weekday Tuesday = new Weekday(2, "--Tuesday--");
    public static readonly Weekday Wednesday = new Weekday(3, "--Wednesday--");
    ....

    private Weekday(int id, string name) : base(id, name)
    {
    }

    public string AppendName(string input)
    {
        return $"{Name} {input}";
    }
}

I know the example is kind of useless, but you get the idea ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.