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,
dropsis defined withvarto be implicitly typed as astring, initialized as empty. - The first
ifstatement uses the remainder operator to check if the is a multiple of3. If so, "Pling" is concatenated todropsusing+. - The second
ifstatement uses the remainder operator to check if the is a multiple of5. If so, "Plang" is concatenated todropsusing+. - The third
ifstatement uses the remainder operator to check if the is a multiple of7. If so, "Plong" is concatenated todropsusing+.
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.
4th Sep 2024
·
Found it useful?