I have two flags:
[Flags] enum Flags { A = 1, B = 2 };
I set them like this:
Mode = Flags.A | Flags.B; // default value for(int i = 0; i < args.Length; i++) { switch(args[i]) { case '--a': { if ((Mode & Flags.A) == Flags.A && (Mode & Flags.B) == Flags.B) // both, default assume { Mode = Flags.A; // only A } else { Mode |= Flags.A; // append A } break; } case '--b': { if ((Mode & Flags.A) == Flags.A && (Mode & Flags.B) == Mode.B) { Mode = Flags.B; } else { Mode |= Flags.B; } break; } } }
and use them later like this:
if((Mode & Flags.A) == Flags.A) { // } if((Mode & Flags.B) == Flags.B) { // }
Major reservation: Both flags may be set. Or just one, in this case only one part of code is executed.
Is my code good? What is the best way to setup flags?
Upd: Is this less ugly then first, how do you think?
Mode = 0; // default value now is empty for(int i = 0; i < args.Length; i++) { switch(args[i]) { case '--a': { Mode |= Flags.A; break; } case '--b': { Mode |= Flags.B; break; } } } if(Mode == 0) { Mode = Flags.A | Flags.B; // if no parameters are given, setup both flags }
Here’s how I would set my flags:
If both flags should be on by default, I think it makes more sense to change the command line parameters to something like
--not-aand--not-b. This would both reflect the default setting, and let you get rid of(Mode & Flags.A) == Flags.A && (Mode & Flags.B) == Flags.B, which is rather ugly, IMHO.Then you can set your flags like this:
Finally, if you have a lot of flags (instead of just two), it might be easier to set up your enum like this: