I'm currently reading the book C# 4.0 in a Nutshell, which by the way I think is an excellent book, even for advanced programmers to use as a good reference.
I was looking back on the chapters about the basics, and I came across a trick to tell if a certain value is defined in an Enum when using flagged enums.
The book states that using Enum.IsDefined
doesn't work on flagged enums, and suggests a work-around like this :
static bool IsFlagDefined(Enum e)
{
decimal d;
return (!decimal.TryParse(e.ToString(), out d);
}
This should return true if a certain value is defined in an enum which is flagged.
Can someone please explain to me why this works ?
Thanks in advance :)
If the value of
e
isn't can't be created using a combination of flagsToString()
defaults to an integral number. And integral numbers will of course parse asdecimal
.But why your code parses as decimal isn't entirely clear to me. But probably integral types won't work for both
enum
s that are based inInt64
andUInt64
.Basically, calling
ToString
on anyenum
value of a type declared with the[Flags]
attribute will return something like this for any defined value:On the other hand, if the value is not defined within the
enum
type, thenToString
will simply produce a string representation of that value's integer value, e.g.:So what this means is that if you can parse the output of
ToString
as a number (not sure why the author chosedecimal
), it isn't defined within the type.Here's an illustration:
The output of the above program is:
So you can see how the suggested method works.