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.
An enumeration type (or enum type) is a value type defined by a set of named constants of the underlying integral numeric type. To define an enumeration type, use the enum keyword and specify the names of enum members: C# Copy. enum Season { Spring, Summer, Autumn, Winter }
You can use CAST() to convert any integer or floating-point type to BOOLEAN : a value of 0 represents false , and any non-zero value is converted to true . You can cast DECIMAL values to BOOLEAN , with the same treatment of zero and non-zero values as the other numeric types. You cannot cast a BOOLEAN to a DECIMAL .
In C#, an enum (or enumeration type) is used to assign constant names to a group of numeric integer values. It makes constant values more readable, for example, WeekDays. Monday is more readable then number 0 when referring to the day in a week.
Prefer Enums and Avoid Booleans An enumerator is a data type consisting of a set of named values that can be used in a type-safe way. While it may not look as simple as a boolean, using an enum or other user-defined type helps us avoid setting up complicated if statements with multiple branches.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With