|
4 | 4 |
|
5 | 5 | Multiple expressions or statements in one line increase the mental burden while reading them. Split them up to avoid mentally hiding statements.
|
6 | 6 |
|
7 |
| -## Prefer logical operators to if statements |
8 |
| - |
9 |
| -```csharp |
10 |
| -if (node.GetParenthesis(key)) |
11 |
| -{ |
12 |
| - item.Setting = false; |
13 |
| -} |
14 |
| -else |
15 |
| -{ |
16 |
| - item.Setting = true; |
17 |
| -} |
18 |
| -``` |
19 |
| -*Avoid if and ternary operator for logical expressions* |
20 |
| - |
21 |
| -Logical expressions have no branches, are more concise and always handle all the logical cases. |
22 |
| - |
23 |
| -```csharp |
24 |
| -item.Setting = !GetParenthesis(key); |
25 |
| -``` |
26 |
| -*Use logical operators `!`, `&&` and `||`* |
27 |
| - |
28 |
| - |
29 | 7 | ## If-statements
|
30 | 8 |
|
31 | 9 | The condition of the if-statement should have no side effects.
|
@@ -59,50 +37,6 @@ if (!updateIsReady)
|
59 | 37 | ```
|
60 | 38 | *Better alternative*
|
61 | 39 |
|
62 |
| -## ternary operator |
63 |
| - |
64 |
| -Prefer the ternary operator to simple if statements. The ternary operator is an expression in contrast to the if-statement and it forces you to handle all the cases. |
65 |
| - |
66 |
| -We format the ternary operator like this, to see which branch we are dealing with easily. |
67 |
| - |
68 |
| -```csharp |
69 |
| -return condition |
70 |
| - ? true-expression |
71 |
| - : false-expression; |
72 |
| -``` |
73 |
| -*ternary operator* |
74 |
| - |
75 |
| -## Switch Expression |
76 |
| - |
77 |
| -Prefer [switch expressions] over switch statements. |
78 |
| - |
79 |
| -```csharp |
80 |
| -return animalKind switch |
81 |
| -{ |
82 |
| - AnimalKind.Dog => "dog", |
83 |
| - AnimalKind.Cat => "cat", |
84 |
| - _ => throw new InvalidOperationException($"Unsupported animal kind {animalKind}"), |
85 |
| -}; |
86 |
| -``` |
87 |
| -*switch expression* |
88 |
| - |
89 |
| -[switch expressions]: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/switch-expression |
90 |
| -
|
91 |
| -## Expression-bodied Members |
92 |
| - |
93 |
| -Use the [expression body syntax] when a member returns a single expression. |
94 |
| -Move the arrow to the next line when the expression gets too long. |
95 |
| - |
96 |
| -```csharp |
97 |
| -public int Length => 0; |
98 |
| - |
99 |
| -public string AbsolutePath() |
100 |
| - => Path.Combine(CalculateRootPath(), RelativePath); |
101 |
| -``` |
102 |
| -*expression-bodied members* |
103 |
| - |
104 |
| -[expression body syntax]: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/expression-bodied-members |
105 |
| -
|
106 | 40 | ## For-loops
|
107 | 41 |
|
108 | 42 | Avoid for-loops and use LINQ and higher order functions as an alternative.
|
|
0 commit comments