Tutorial :can C# enums be declared as of bool type?



Question:

Can I declare c# enum as bool like:

enum Result : bool  {      pass = true,      fail = false  }  


Solution:1

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;  }  


Solution:2

It says

The approved types for an enum are byte, sbyte, short, ushort, int, uint, long, or ulong.

enum (C# Reference)


Solution:3

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)


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »