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 withvar
to be implicitly typed as astring
, initialized as empty. - The first
if
statement uses the remainder operator to check if the is a multiple of3
. If so, "Pling" is concatenated todrops
using+
. - The second
if
statement uses the remainder operator to check if the is a multiple of5
. If so, "Plang" is concatenated todrops
using+
. - The third
if
statement uses the remainder operator to check if the is a multiple of7
. If so, "Plong" is concatenated todrops
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.
6th Nov 2024
·
Found it useful?