1

I have this enum:

[Flags]
public enum SearchFormattings
{
    None = 0,
    ToLower = 1,
    NoPunctuationSerialNumber = 2
}

Then a variable is assigned and HasFlag is called:

var searchFormatting = SearchFormattings.ToLower | SearchFormattings.NoPunctuationSerialNumber;

I expect the following line to return false but it always returns true. What did I miss?

searchFormatting.HasFlag(SearchFormattings.None)

Matthias Herrmann
  • 2,650
  • 5
  • 32
  • 66
  • 6
    "None" is not a flag. An ArgumentException would have been useful, but they did it by documenting "If the underlying value of flag is zero, the method returns true". – Hans Passant Mar 04 '20 at 14:41
  • `anyNumber & 0 == 0` will always be true (should be equivalent as `anyNumber.HasFlag(0)`) – Cid Mar 04 '20 at 14:42
  • Also see: [Why should I never use 0 in a flag enum](https://stackoverflow.com/questions/9811047/why-should-i-never-use-0-in-a-flag-enum) –  Mar 04 '20 at 14:43
  • 1
    https://learn.microsoft.com/en-us/dotnet/api/system.enum.hasflag?view=netframework-4.8 - "If the underlying value of flag is zero, the method returns true." – Christoph Lütjen Mar 04 '20 at 14:43
  • Yep that answers my question - ty – Matthias Herrmann Mar 04 '20 at 14:45

0 Answers0