Hi,
Can I declare c# enum
as bool
like:
enum Result : bool
{
pass = true,
fail = false
}
Hi,
Can I declare c# enum
as bool
like:
enum Result : bool
{
pass = true,
fail = false
}
It says
The approved types for an enum are byte, sbyte, short, ushort, int, uint, long, or ulong.
Hi, if you need your enum to contain boolean data in addition to the enum constant's type value, you could add a simple attribute to your enum, taking a boolean value. Then you can add an extension method for your enum that fetches the attribute and returns its boolean value.
public class MyBoolAttribute: Attribute
{
public MyBoolAttribute(bool val)
{
Passed = val;
}
public bool Passed
{
get;
set;
}
}
public enum MyEnum
{
[MyBoolAttribute(true)]
Passed,
[MyBoolAttribute(false)]
Failed,
[MyBoolAttribute(true)]
PassedUnderCertainCondition,
... and other enum values
}
/* the extension method */
public static bool DidPass(this Enum en)
{
MyBoolAttribute attrib = GetAttribute<MyBoolAttribute>(en);
return attrib.Passed;
}
/* general helper method to get attributes of enums */
public static T GetAttribute<T>(Enum en) where T : Attribute
{
Type type = en.GetType();
MemberInfo[] memInfo = type.GetMember(en.ToString());
if (memInfo != null && memInfo.Length > 0)
{
object[] attrs = memInfo[0].GetCustomAttributes(typeof(T),
false);
if (attrs != null && attrs.Length > 0)
return ((T)attrs[0]);
}
return null;
}
What about:
class Result
{
private Result()
{
}
public static Result OK = new Result();
public static Result Error = new Result();
public static implicit operator bool(Result result)
{
return result == OK;
}
public static implicit operator Result( bool b)
{
return b ? OK : Error;
}
}
You can use it like Enum or like bool, for example var x = Result.OK; Result y = true; if(x) ... or if(y==Result.OK)