Enum flag and None value

74 Views Asked by At

I was playing around with the SslPolicyErrors enum and noticed the following behavior:

SslPolicyErrors error = SslPolicyErrors.RemoteCertificateChainErrors
                      | SslPolicyErrors.None
                      | SslPolicyErrors.RemoteCertificateNameMismatch;

Console.WriteLine(error.HasFlag(SslPolicyErrors.None));
Console.WriteLine(error.HasFlag(SslPolicyErrors.RemoteCertificateChainErrors));
Console.WriteLine(error.HasFlag(SslPolicyErrors.RemoteCertificateNameMismatch));

I would expect the first print for the None flag to be false, but to my surprise all three prints were true:

True
True
True

So I looked up the source and found this:

    [Flags]
    public enum SslPolicyErrors
    {
        None                          = 0x0,
        RemoteCertificateNotAvailable = 0x1,
        RemoteCertificateNameMismatch = 0x2,
        RemoteCertificateChainErrors  = 0x4
    }

Which was exactly what I expected initially, but I don't understand how an instance can both have the None flag and at the same time one or more other flags.

1

There are 1 best solutions below

0
Jurgy On

Question was answered in the comments but for completeness sake I will answer it myself.

From the docs itself:

The HasFlag method returns the result of the following Boolean expression.

thisInstance And flag = flag

If the underlying value of flag is zero, the method returns true. If this behavior is not desirable, you can use the Equals method to test for equality with zero and call HasFlag only if the underlying value of flag is non-zero, as the following example illustrates.

So for zero flags you have to do flag == Flags.None instead of flag.HasFlag(Flags.None)