Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum Extension Method is not showing

Tags:

c#

enums

I'm trying to add new/extension method for Enum but the extension method is not showing on intellisense method list. Please help here's my code.

Extension:

public static class EnumExtensions
    {
        public static string GetDescriptionAttr(this Enum value,string key)
        {
            var type = value.GetType();
            var memInfo = type.GetMember(key);
            var attributes = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute),
                false);
            var description = ((DescriptionAttribute)attributes[0]).Description;
            return description;
        }
    }

Trying to call the result from other class (both caller and extension are in the same project)

enter image description here

like image 520
Jobert Enamno Avatar asked Oct 26 '25 08:10

Jobert Enamno


2 Answers

Extension methods can be applied on instances only

public static class EnumExtensions {
  // This extension method requires "value" argument
  // that should be an instance of Enum class 
  public static string GetDescriptionAttr(this Enum value, string key) {
    ...
  }
}

...

public enum MyEnum {
  One, 
  Two,
  Three
}

Enum myEnum = MyEnum.One;

// You can call extension method on instance (myEnum) only
myEnum.GetDescriptionAttr("One");
like image 75
Dmitry Bychenko Avatar answered Oct 28 '25 23:10

Dmitry Bychenko


You should use extension method for an instance of your enum. I have this code and it works properly:

public static string GetDescription(this Enum value)
{
    var attributes = 
        (DescriptionAttribute[])value.GetType().GetField(value.ToString())
        .GetCustomAttributes(typeof(DescriptionAttribute), false);
    return attributes.Length > 0 ? attributes[0].Description : value.ToString();
}

And using of this method shows here:

MyEnum myE = MyEnum.OneOfItemsOfEnum;
string description = myE.GetDescription();
like image 28
Merta Avatar answered Oct 28 '25 22:10

Merta