I am going to expand upon @OlivierJacot-Descombes answer and offer an alternative. You do not have to limit yourself to a single method signature. And you do not have to use a BitArray
. My answer is strictly offered as an alternative but I make no claim as to performance. But since the backing data storage to a BitArray
is an internal int[]
, much of the bit-twiddling I perform is also performed by BitArray
.
public void SetConfiguration(bool mode1,
bool mode2,
bool mode3,
bool mode4,
bool mode5,
bool mode6,
bool mode7,
bool mode8)
=> SetConfiguration(new bool[] { mode1, mode2, mode3, mode4, mode5, mode6, mode7, mode8 });
public static void SetConfiguration(params bool[] modes)
{
if (modes == null)
{
throw new ArgumentNullException(nameof(modes));
}
if (modes.Length != 8)
{
throw new ArgumentException($"Array {nameof(modes)} must have a Length of 8.");
}
byte result = (byte)(modes[0] ? 1 : 0);
for (int i = 1; i < modes.Length; i++)
{
if (modes[i])
{
result += (byte)(2 << (i - 1));
}
}
_mode = result;
}
MORE THINGS TO CONSIDER
ONE BIT AT A TIME
If you intend to sometimes fiddle with only a single flag or bit at a time, you may want to consider this method signature:
public void SetConfiguration(bool mode1 = false,
bool mode2 = false,
bool mode3 = false,
bool mode4 = false,
bool mode5 = false,
bool mode6 = false,
bool mode7 = false,
bool mode8 = false)
=> SetConfiguration(new bool[] { mode1, mode2, mode3, mode4, mode5, mode6, mode7, mode8 });
NAMING
Your name choice of mode reflects the mode of configuration. I get that. But these methods are manipulating flags or bits, so the naming could be changed to reflect that with parameters of flag1
or bit1
. BUT I would also then suggest the parameter names should reflect 0-indexing. Thus, flag0
or bit0
.
RETURN INT
The SetConfiguration
is a void
but it sets a class level object named _mode
. The bit-twiddling part could be a more generalized, static method that returns an int
. This would make it reusable anywhere you want to twiddle with bits and return an integer. If you do this, then the method name would need to be changed since it no longer sets a value, but rather would get a value.
BitArray
ctor which acceptsbool[]
? \$\endgroup\$