Home > Mobile >  C# Enums are always none
C# Enums are always none

Time:09-02

In C#, i have the following enum. i want to be able to run my verification function an return the issues found via said enum, but it seems to always contain OK.

everything ive read on this says to use 0 for none, which, to me at least, seems logically equivalent to OK, as there are "none" problems. but if i check "enum.HasFlag(ValidationResult.OK)" it will return true 100% of the time, no matter how many others are set. i feel like if it doesnt equal 0, it shouldnt say it does. this seems broken to me.

What is the proper way to deal with this?

[Flags]
public enum ValidationResult
{
    OK,
    NotOK,
    ReallyNotOk
}
void Main()
{
    var x = ValidationResult.OK;
    Console.Write(x.HasFlag(ValidationResult.OK)); // true
    
    
    var y = ValidationResult.NotOk;
    Console.Write(y.HasFlag(ValidationResult.OK)); // still true for some reason
}

CodePudding user response:

0 isn't a flag, it is the complete absence of flags. If the flags represent different types of failures, then it may be appropriate to give the label Ok to 0... but it still isn't a flag and cannot be tested with HasFlag.

Console.Write(y == ValidationResult.OK); // works correctly

CodePudding user response:

namespace EnumTest
{
    [Flags]
    public enum ValidationResult
    {
        None = 0,
        OK = 1,
        NotOK = 2,
        ReallyNotOk = 4
    }

    class Program
    {
        static void Main(string[] args)
        {
            ValidationResult x = ValidationResult.OK;
            Console.Write(x.HasFlag(ValidationResult.OK)); // true

            ValidationResult y = ValidationResult.NotOK;
            Console.Write(y.HasFlag(ValidationResult.OK)); // Result False

            ValidationResult z = ValidationResult.NotOK | ValidationResult.ReallyNotOk;
            Console.Write(z.HasFlag(ValidationResult.OK)); // Result False
        }
    }
}

CodePudding user response:

In addition to the answer of Ben Voigt, you can fix this by adding desired values manually like:

[Flags]
public enum ValidationResult
{
    OK = 1,
    NotOK = 2,
    ReallyNotOk = 4
}

Update:

As Ben pointed out in his comment, the presented solution lacks the possibility to present EITHER "OK" OR a concrete failure state. Thus I would propose using a class hierarchy instead of an enumeration.

A simple example can be found in the microsoft docs: Use enumeration classes instead of enum types

  • Related