Aviran Katz Aviran Katz - 2 months ago 11
C# Question

Is there a way to simply resemble a truth table?

Is there any simple way to resemble a truth table in code? It has 2 inputs and 4 outcomes, as shown below:

enter image description here

My current code is:

private void myMethod(bool param1, bool param2)
{
Func<int, int, bool> myFunc;
if (param1)
{
if (param2)
myFunc = (x, y) => x >= y;
else
myFunc = (x, y) => x <= y;
}
else
{
if (param2)
myFunc = (x, y) => x < y;
else
myFunc = (x, y) => x > y;
}
//do more stuff
}

Answer

I suggest using an array, i.e.

  // XOR truth table
  bool[][] truthTable = new bool[][] {
    new bool[] {false, true},
    new bool[] {true, false},
  };

...

  private void myMethod(bool param1, bool param2, bool[][] table) {
    return table[param1 ? 0 : 1][param2 ? 0 : 1];
  }