Enumeration to boolean casting question
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);
Related videos on Youtube
greggorob64
The best winforms developer you'll find in all of my cubicle. C#\Visual C++\C
Updated on July 09, 2022Comments
-
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 almost 13 yearsI'm new to the .net 3.5 world, I forgot this feature existed, I'll give it a try, thanks.
-
rbleattler about 2 yearsThanks 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!