Multi switch statement with single variable?
Community Forums/General Help/Multi switch statement with single variable?
| ||
Hi guys, Quick programming question (in C#) but how do you do a multi switch argument statement with a single variable? I used to know how to do it but I've forgotten and I can't seem to get the syntax correct. I know what you do is have a parameter and use the single | statement to grab each bit. For example. Psuedo Code MOO = 1 POO = 2 PLOP = 4 MOOSE = 8 myparam = MOO + PLOP; switch (myparam) { case | MOO // Code break; case | POO // Code break; case | PLOP // Code break; case | MOOSE // Code break; } Or something like this Can anyone point out where I am going wrong? :) |
| ||
I honestly don't get what you're trying to do with that | operator. That's not valid C# syntax and ...that doesn't look like the switch statement's intended use, either. You can find an example of using switch here: http://en.wikipedia.org/wiki/Switch_statement#C.23 ...but perhaps a BlitzMax translation of what you want the code to do is in order, because you're clearly going for something more involved? I have the feeling what you want won't work with switch, because switch needs to be able to compile to a jump table (may be implemented as If behind the scenes, but that's unrelated) and therefore can't have dynamic expressions as the case arguments: everything needs to be constant. If you want each arm to take apart a runtime value, you probably need to use a chain of if statements each with their own expression test. |
| ||
That was merely Psuedo Code. It is like when you do an AND operation on a 8 bit. if (myparam | MOO) { } if (myparam | POO) { } Blitz3D uses on LoadImage when you pass a flag in there, you have COLOR + BITMAP which is if I recall 1 + 8. I want the opposite of that. |
| ||
...I don't think you can use switch for that, unless there's some extra switch syntax C# added on top of what it inherited. I think you have to do it with ordered operations. Simplest:if (myparam & MOO != 0) { ... } else if (myparam & POO != 0) { ... } Or, more needlessly complicated but possibly closer to the idiom you want: var actions = new Dictionary<int, Func<int, int>> { { MOO, x => { return doSomething(x); } } { POO, x => { return doSomething(x); } } ... }; foreach(KeyValuePair<int, Func<int, int>> act in actions) { if (myparam & act.Key != 0) return act.Value(act.Key); } |
| ||
Thanks for your help Yasha, I appreciate it. :) I finally figured out what I was trying to do. It was a bitmask switch statement I needed. Something like this. http://stackoverflow.com/questions/6607627/bitmask-switch-statement I suck at explaining my problems! Sorry about that. I could lie but sadly English is my first language so I have no excuses ;) |