c# - Can I avoid casting an enum value when I try to use or return it? -
if have following enum:
public enum returnvalue{ success = 0, failreason1 = 1, failreason2 = 2 //etc... }
can avoid casting when return, this:
public static int main(string[] args){ return (int)returnvalue.success; }
if not, why isn't enum value treated int default?
enums supposed type safe. think didn't make them implicitly castable discourage other uses. although framework allows assign constant value them, should reconsider intent. if use enum storing constant values, consider using static class:
public static class returnvalue { public const int success = 0; public const int failreason1 = 1; public const int failreason2 = 2; //etc... }
that lets this.
public static int main(string[] args){ return returnvalue.success; }
edit
when do want provide values enum when want combine them. see below example:
[flags] // indicates bitwise operations occur on enum public enum daysofweek : byte // byte type limit size { sunday = 1, monday = 2, tuesday = 4, wednesday = 8, thursday = 16, friday = 32, saturday = 64, weekend = sunday | saturday, weekdays = monday | tuesday | wednesday | thursday | friday }
this enum can consumed using bitwise math. see below example applications.
public static class daysofweekevaluator { public static bool isweekends(daysofweek days) { return (days & daysofweek.weekend) == daysofweek.weekend; } public static bool isallweekdays(daysofweek days) { return (days & daysofweek.weekdays) == daysofweek.weekdays; } public static bool hasweekdays(daysofweek days) { return ((int) (days & daysofweek.weekdays)) > 0; } public static bool hasweekenddays(daysofweek days) { return ((int) (days & daysofweek.weekend)) > 0; } }
Comments
Post a Comment