I'm still at my early beginning in C# and I'm trying to implement Enum/converter converters.
All my enums has a NotDefined
value equals to -1
.
I would like to implement a generic extension method to get an enum from a string base on the the enum description (which mostly differ in spaces and cases).
public static T ToEnum<T>(this string value) where T : struct
{
foreach (T e in Enum.GetValues(typeof(T)))
{
if (e.GetDescription() ==value)
{
return e;
}
}
// Doesn't work..
// How can I return T.NotDefined? - I don't really want to throw something here
return (T)-1;
}
PS I initially found the GetDescription() implementation thanks to this thread : Enum ToString with user friendly strings which helps me a lot :-) .
Does anyone have an insight about my issue?
Many thanks!
Aucun commentaire:
Enregistrer un commentaire