S
Shapper
Hello,
I have the following Enum:
public enum FruitsEnum {
[FruitColor("Red")]
Apple = 1,
[FruitColor("Green")]
Kiwi = 2,
[FruitColor("Yellow")]
Pear = 3
};
The FruitColor attribute is as follows:
public sealed class FruitColorAttribute : Attribute {
public String Color { get; set; }
public FruitColorAttribute(String color) {
this.Color = color;
}
}
I have two extensions (Name and Value):
public static class FruitEnumExtensions {
public static String Name(this FruitsEnum value) {
return Enum.IsDefined(typeof(FruitsEnum), value) ? Enum.GetName(typeof(FruitsEnum), value) : null;
}
public static Int32? Value(this FruitsEnum value) {
return Enum.IsDefined(typeof(FruitsEnum), value) ? (Int32?)value : new Nullable<Int32>();
}
}
But when I try to use it as follows:
String name = FruitsEnum.Apple.Name;
Int32? value = FruitsEnum.Apple.Value;
And I get the following errors:
Cannot convert method group 'Name' to non-delegate type 'string'. Did you intend to invoke the method?
Cannot convert method group 'Value' to non-delegate type 'int?'. Did you intend to invoke the method?
1 - What am I doing wrong?
2 - Is it possible to make the extensions generic and apply it to any Enum?
3 - How can I make an extension to get the value of an Attribute given its type?
Something like: myEnum.GetAttribute<FruitColorAttribute>();
Thank You,
Miguel
I have the following Enum:
public enum FruitsEnum {
[FruitColor("Red")]
Apple = 1,
[FruitColor("Green")]
Kiwi = 2,
[FruitColor("Yellow")]
Pear = 3
};
The FruitColor attribute is as follows:
public sealed class FruitColorAttribute : Attribute {
public String Color { get; set; }
public FruitColorAttribute(String color) {
this.Color = color;
}
}
I have two extensions (Name and Value):
public static class FruitEnumExtensions {
public static String Name(this FruitsEnum value) {
return Enum.IsDefined(typeof(FruitsEnum), value) ? Enum.GetName(typeof(FruitsEnum), value) : null;
}
public static Int32? Value(this FruitsEnum value) {
return Enum.IsDefined(typeof(FruitsEnum), value) ? (Int32?)value : new Nullable<Int32>();
}
}
But when I try to use it as follows:
String name = FruitsEnum.Apple.Name;
Int32? value = FruitsEnum.Apple.Value;
And I get the following errors:
Cannot convert method group 'Name' to non-delegate type 'string'. Did you intend to invoke the method?
Cannot convert method group 'Value' to non-delegate type 'int?'. Did you intend to invoke the method?
1 - What am I doing wrong?
2 - Is it possible to make the extensions generic and apply it to any Enum?
3 - How can I make an extension to get the value of an Attribute given its type?
Something like: myEnum.GetAttribute<FruitColorAttribute>();
Thank You,
Miguel