Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create extension method for Enum type argument?

Following is my code to convert enum values to Dictionary.

public static Dictionary<string, string> EnumToDictionary<T>() where T : struct, IConvertible
    {
        var oResult = new Dictionary<string, string>();
        if (typeof(T).IsEnum)
            foreach (T oItem in Enum.GetValues(typeof(T)))
                oResult.Add(oItem.ToString(), oItem.ToString());
        return oResult;
    }

and this is my enum

public enum MyEnum
{
    Value1,
    Value2,
    value3
}

Currently I am calling that method like

var result=EnumToDictionary<MyEnum>();

but I need to use that method like

var result=MyEnum.EnumToDictionary();

or any other way like string extension methods.

like image 331
Mehul Patel Avatar asked Jan 23 '14 11:01

Mehul Patel


People also ask

How do you declare an extension method?

An extension method must be defined in a top-level static class. An extension method with the same name and signature as an instance method will not be called. Extension methods cannot be used to override existing methods. The concept of extension methods cannot be applied to fields, properties or events.

Can you extend enum Java?

No, we cannot extend an enum in Java. Java enums can extend java. lang. Enum class implicitly, so enum types cannot extend another class.

Can we extend enum in C#?

You can cast the enum back and forth between ints, and Enum has some helper functions that can help when working with enums. But that's about it for C#, they are much like C or C++ enums. Show activity on this post. You can do something similar in C# using Extension methods.

Can you use extension to add functionality to an enumeration?

You can use extension methods to add functionality specific to a particular enum type.


2 Answers

In general your problem is connected with the fact that you want to create a generic extensions method (that's possible) but without any object reference sent as "this" parameter when calling such a method (that's not possible). So using extension methods is not an option to achieve what you want.

You could do sth like this:

public static Dictionary<string, string> EnumToDictionary(this Enum @enum)
{
    var type = @enum.GetType();
    return Enum.GetValues(type).Cast<string>().ToDictionary(e => e, e => Enum.GetName(type, e));
}

But this would mean that you need to operate on a certain instance of enum class to call such an extension method.

Or you could do this in such a way:

    public static IDictionary<string, string> EnumToDictionary(this Type t)
    {
        if (t == null) throw new NullReferenceException();
        if (!t.IsEnum) throw new InvalidCastException("object is not an Enumeration");

        string[] names = Enum.GetNames(t);
        Array values = Enum.GetValues(t);

        return (from i in Enumerable.Range(0, names.Length)
                select new { Key = names[i], Value = (int)values.GetValue(i) })
                    .ToDictionary(k => k.Key, k => k.Value.ToString());
    }

And then call it like this:

var result = typeof(MyEnum).EnumToDictionary();
like image 108
Paweł Bejger Avatar answered Nov 14 '22 22:11

Paweł Bejger


You could write an extension method, something like:

    public static IDictionary<string, string> ToDictionary(this Enum value)
    {
        var result = new Dictionary<string, string>();
            foreach (var item in Enum.GetValues(value.GetType()))
                result.Add(Convert.ToInt64(item).ToString(), item.ToString());
        return result;
    }

But to call such an extension method, you need to provide an instance of the required enum. E.g.

        var dict = default(System.DayOfWeek).ToDictionary();
like image 36
Joe Avatar answered Nov 14 '22 23:11

Joe