Is an empty flag a bad habit?

I ran into a very dumb mistake a few days ago. This is caused by this listing, which I get from a third-party library:

[Flags]
public enum MyStatus
{
    OKResponse = 0,
    ResponseTooBig = 1,
    ErrorMessage = 2,
    NoResponse = 4,
    ...
}

I use flags this way:

if ((status & MyStatus.OKResponse) != 0) {...}

but it does not work for MyStatus.OKResponse, because it is zero. This is not a flag at all, it is the absence of all flags. Of course, when I discovered the error, I realized that it OKResponsewas the only error status, so it really means "no errors, no flags." However, I really do not think this is obvious.

Is this a bad habit defining 0 as one of the values ​​in the flag enumeration? What is the recommended way? What is the best way to check flags that will also work with the "no flags" flag?

+4
2

, 0 ?

, , , 0 , , , , , Enum.None , , .

?

, Enum.HasFlag:

void Main()
{
    var status = MyStatus.ResponseTooBig | MyStatus.NoResponse;
    if (status.Equals(MyStatus.OKResponse))
        Console.WriteLine("Status is OKResponse");
    else 
        Console.WriteLine($"Has NoResponse?: {status.HasFlag(MyStatus.NoResponse)}");
}
+6

0 , OK, 0 , , , :

MyStatus status = 0;

, 0 , , None Flags enums Invalid .

, Flags , , , .

, , , , , OK, , , Flags, , , OKResponse:

if (status == MyStatus.OKResponse)
+1

All Articles