-1

I'm using this code right now where Settings.noa is an integer:

var pointsText =   Settings.noa == 1  ? " one point" : " points";

But what I would like to do without a lot of if-else is to have this output:

one point, two points, three points, four points or five points.

note that Settings.noa can only be in the range of 1-5

Alan2
  • 23,493
  • 79
  • 256
  • 450

1 Answers1

1

That's a horrible way to code, but if you are hell bent on doing it in one statement:

var pointsText = Settings.noa == 1  ? " one point" :
    Settings.noa == 2  ? " two points" : 
    Settings.noa == 3  ? " three points" : 
    Settings.noa == 4  ? " four points" : 
    Settings.noa == 5  ? " five points" : "Unexpected input";

Personally I'd create a separate method, like this:

private string ConvertToPointsText(int input)
{
    if (input < 1 || input > 5) 
        throw new ArgumentOutOfRangeException(nameof(input), 
        "Must be between 1 and 5 inclusive.");

    switch (input)
    {
        case 1: return "one point";
        case 2: return "two points";
        case 3: return "three points";
        case 4: return "four points";
        case 5: return "five points";

        // this is redundant but here to stop the compiler from complaining.
        default: throw new Exception("Unknownn value: " + input); 
    }
}

and use it like:

string pointsText = ConvertToPointsText(Settings.noa);
rory.ap
  • 34,009
  • 10
  • 83
  • 174