So I am new to C#, but one thing I already like coming from other higher level languages is the ability to do bitwise operations in (close to) C. I have a bunch of functions where some or all parameters are optional, and I like switches, so I built a function that converts boolean arrays to unsigned Shorts which allows me to basically Mux a boolean array to a single value for the switch:
namespace firstAsp.Helpers{
public class argMux{
public static ushort ba2ushort (bool[] parms){
//initialize position and output
ushort result = 0;
int i = parms.Length-1;
foreach (bool b in parms){
if (b)//put a one in byte at position of b
//bitwise or with position
result |= (ushort)(1<<i);
i--;
}
return result;
}
}
}
Here is an example use case:
public IActionResult Cheese(string fname,string lname)
{
bool[] tf = {fname!=null,lname!=null};
switch(argMux.ba2ushort(tf)){
case 3:
@ViewData["Data"]=$"Hello, {fname} {lname}";
break;
case 2:
@ViewData["Data"]=$"Hello, {fname}";
break;
case 1:
@ViewData["Data"]=$"Hello, Dr. {lname}";
break;
case 0:
@ViewData["Data"]="Hello, Dr. CheeseBurger";
break;
}
return View();
}
My question is, Is this an efficient way to do this, or is there a way that is superior? I am aiming for simplicity of use which this definitely delivers for me, but I would also like it to be efficient code that is fast at runtime. Any pointers? Is this a stupid way to do this? Any and all feedback is welcome, you can even call me an idiot if you believe it, I'm not too sensitive. Thanks!