if statements

Raindrops
Raindrops in C#
public static class Raindrops
{
    public static string Convert(int number)
    {
        var drops = "";

        if (number % 3 == 0) drops += "Pling";
        if (number % 5 == 0) drops += "Plang";
        if (number % 7 == 0) drops += "Plong";

        return drops.Length > 0 ? drops : number.ToString();
    }
}
  • First, drops is defined with var to be implicitly typed as a string, initialized as empty.
  • The first if statement uses the remainder operator to check if the is a multiple of 3. If so, "Pling" is concatenated to drops using +.
  • The second if statement uses the remainder operator to check if the is a multiple of 5. If so, "Plang" is concatenated to drops using +.
  • The third if statement uses the remainder operator to check if the is a multiple of 7. If so, "Plong" is concatenated to drops using +.

A ternary operator is then used to return drops if it has more than 0 characters, or it returns number.ToString().

Shortening

When the body of an if statement is a single line, both the test expression and the body could be put on the same line, like so

if (number % 3 == 0) drops += "Pling";

The C# Coding Conventions advise to write only one statement per line in the layout conventions section, but the conventions begin by saying you can use them or adapt them to your needs. Your team may choose to overrule them.

11th Dec 2024 · Found it useful?