shortening if statement with same conditions

I'm comparing the boolB here twice, and this code looks like it needs improvement. Is it possible to write this different to reduce code repetition?

if (boolA)
{
  if (boolB)
  {
    return "A";
  }

  return "B";
} 

if (boolB)
{
   return "C";
}

return "D";
Jon Skeet
people
quotationmark

Well, you could a conditional operator to make it clearer - at least to my eyes:

return boolA && boolB ? "A"
    : boolA ? "B"
    : boolB ? "C"
    : "D";

Once you get used to this way of writing multiple conditional operators, it reads very clearly as a sort of pseudo-pattern-matching approach.

This does evaluate conditions multiple times, admittedly. There are ways of avoiding that, but I'm not sure they're nice... for example:

int bits = (boolA ? 2 : 0) | (boolB ? 1 : 0);
switch(bits)
{
    case 3: return "A";
    case 2: return "B";
    case 1: return "C";
    case 0: return "D";
    default: throw new InvalidOperationException("The world has gone mad!");
}

Or use a different approach to the nesting of the conditionals:

return boolA ? (boolB ? "A" : "B")
    : boolB ? "C"
    : "D";

This still expresses boolB as a condition twice, mind you.

people

See more on this question at Stackoverflow