Enumeration to boolean casting question

greggorob64 picture greggorob64 · Jul 11, 2011 · Viewed 19.3k times · Source

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.

Answer

Marc Gravell picture Marc Gravell · Jul 11, 2011

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();