Enumeration to boolean casting question

21,971

Solution 1

That line would work only with an implicit static conversion operator (or maybe the more-confusing true() operator, but that is rarely seen in the wild). You cannot define operators on enums, so ultimately the answer is: no.

You could, however, write an extension method on MyEnum to return true or false.

static class MyEnumUtils {
    public static bool Value(this MyEnum value) {
        switch(value) {
            case MyEnum.MyTrue: return true;
            case MyEnum.MyFalse: return false;
            default: throw new ArgumentOutOfRangeException("value");
                 // ^^^ yes, that is possible
        }
    }
}

then you can use bool IsThisTrue = val.Value();

Solution 2

Write an extension method like this:

public static bool ToBoolean(this MyEnum value) {
    return value == MyEnum.MyTrue;
}

and forget about it

Solution 3

Try this:

public enum MyEnum
{
    MyFalse = 0,
    MyTrue = 1
}

then:

MyEnum val = MyEnum.MyTrue;
bool IsThisTrue = val;

bool IsThisTrue = Convert.ToBoolean((int)val);
Share:
21,971

Related videos on Youtube

greggorob64
Author by

greggorob64

The best winforms developer you'll find in all of my cubicle. C#\Visual C++\C

Updated on July 09, 2022

Comments

  • greggorob64
    greggorob64 almost 2 years

    I have the following enumeration:

    public enum MyEnum
    {
        MyTrue,
        MyFalse
    }
    

    And I'd like to eventually be able to automatically convert my enumeration to a boolean value, with a simple line like this:

    MyEnum val = MyEnum.MyTrue;
    bool IsThisTrue = val;
    

    Currently, I have to do this:

    bool IsThisTrue = val == MyEnum.MyTrue;
    

    Is there some mechanism I can apply to my enumeration to allow for native enum->bool casting? I'm wondering if some variant of a typeconverter is what I need or not.

    Thanks

    Edit: There is a reason for my custom enumeration. Since this properties are all eventually bound to a property grid, we have mechanisms put in place to bind all of our custom enumerations to multi-lingual strings in resources files. We need all of the enum's we're using to be in a specific namespace, hence the "MyEnum" class.

  • greggorob64
    greggorob64 almost 13 years
    I'm new to the .net 3.5 world, I forgot this feature existed, I'll give it a try, thanks.
  • rbleattler
    rbleattler about 2 years
    Thanks for this. It is a bit dizzying though to have to nest the functions like that in inline code. Great baseline for the accepted solution here though!