how do i switch on an enum which have the flags attribute set (or more precisely is used for bit operations) ?
I want to be able to hit all cases in a switch that matche
The easiest way is to just perform an ORed
enum, in your case you could do the following :
[Flags()]public enum CheckType
{
Form = 1,
QueryString = 2,
TempData = 4,
FormQueryString = Form | QueryString,
QueryStringTempData = QueryString | TempData,
All = FormQueryString | TempData
}
Once you have the enum
setup its now easy to perform your switch
statement.
E.g, if i have set the following :
var chkType = CheckType.Form | CheckType.QueryString;
I can use the following switch
statement as follows :
switch(chkType){
case CheckType.Form:
// Have Form
break;
case CheckType.QueryString:
// Have QueryString
break;
case CheckType.TempData:
// Have TempData
break;
case CheckType.FormQueryString:
// Have both Form and QueryString
break;
case CheckType.QueryStringTempData:
// Have both QueryString and TempData
break;
case CheckType.All:
// All bit options are set
break;
}
Much cleaner and you don't need to use an if
statement with HasFlag
. You can make any combinations you want and then make the switch statement easy to read.
I would recommend breaking apart your enums
, try see if you are not mixing different things into the same enum
. You could setup multiple enums
to reduce the number of cases.