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)

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");
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With