i have this code:
[Flags]
public enum MyUriType {
ForParse,
ForDownload,
Unknown
}
and then:
MyUriType uriType = MyUriType.ForDownload;
but, I was wondering why this returns true:
if ((uriType & MyUriType.ForParse) == MyUriType.ForParse)
When it is not set in the second code group. Please advise.
By default, the first field for an
enumtype is given the ordinal value0.So, if
uriTypedoes not contain theMyUriType.ForParseflag, thenuriType & MyUriType.ForParseactually equals0, which counterintuitively evaluates totruewhen you compare it toMyUriType.ForParsefor equality (which is also0).If you break it down to bitwise arithmetic then the expression you’re evaluating is:
…which will always evaluate to
true, no matter what the “something” is.Normally, when you define a
Flagsenum, you should actually specify values for each field:Each value should be a power of 2 so that they don’t conflict (every multiple of 2 is a binary shift-left).
It’s also customary to name it as a plural, so that people who use the enum know that it is a
Flagsenum and can/should hold multiple values.If you define your enum this way, your test code will now evaluate to
falseifuriTypedoes not have theForParsebit set.