Enums + Extension Methods = Sweet
Intro
Have you ever wanted to get an enum's description instead of it's ToString() representation? I know I did.
Just override ToString()? Enum's don't allow overrides. Just use some method that switches based on the enum value? Switches are evil!
Enter extension methods. Do you know that you can extend an enum?
The following is perfectly legal code:
public static string DoSomethingWith(SomeEnum some){ //... }
From that I got the idea of extending Enum itself to add the following to the given enum:
public enum SomeEnum{
[Description("Some Value")]
SomeValue = 1
}
- GetValue() - Returns the enum value as integer - i.e.: SomeEnum.SomeValue.GetValue(); - Returns 1
- GetName() - Returns the description for a given enum value (use DescriptionAttribute to assign a description to each value) - i.e.: SomeEnum.SomeValue.GetName(); - Returns "Some Value"
- GetValueAsString() - Returns GetValue().ToString() - i.e.: SomeEnum.SomeValue.GetValueAsString() - Returns "1"
Conclusion
I included the project that uses that as an attachment! I'll definitely be using that in the future. Happy coding!