Given the listing
enum Foo{A, B, C}
the code below converts from enumto stringand vice versa:
var values =
from name in Enum.GetNames(typeof(Foo))
select (Foo)Enum.Parse(typeof(Foo), name, true);
So yes, casting works. However, keep in mind that the above request will call the method ArgumentExceptionif the method Enum.Parsereceives a value that cannot be parsed.
This updated version only returns values that are processed successfully.
enum Foo{A, B, C}
var values =
from name in Enum.GetNames(typeof(Foo))
where Enum.IsDefined(typeof(Foo), name)
select (Foo)Enum.Parse(typeof(Foo), name, true);
source
share