|
1 | 1 | using System; |
2 | | -using System.Collections.Generic; |
3 | | -using System.Text; |
4 | 2 |
|
5 | 3 | namespace operators |
6 | 4 | { |
7 | 5 | public class ConditionalExamples |
8 | 6 | { |
9 | 7 | public static void Examples() |
10 | 8 | { |
| 9 | + ConditionalRefExpressions(); |
11 | 10 | ConditionalValueExpressions(); |
| 11 | + ComparisonWithIf(); |
12 | 12 | } |
13 | 13 |
|
14 | | - static void ConditionalRefExpressions() |
| 14 | + private static void ConditionalRefExpressions() |
15 | 15 | { |
16 | 16 | // <SnippetConditionalRef> |
17 | 17 | var smallArray = new int[] { 1, 2, 3, 4, 5 }; |
18 | 18 | var largeArray = new int[] { 10, 20, 30, 40, 50 }; |
19 | 19 |
|
20 | | - int index= new Random().Next(0, 9); |
| 20 | + int index = 7; |
21 | 21 | ref int refValue = ref ((index < 5) ? ref smallArray[index] : ref largeArray[index - 5]); |
22 | | - Console.WriteLine(refValue); |
| 22 | + refValue = 0; |
| 23 | + |
| 24 | + index = 2; |
| 25 | + ((index < 5) ? ref smallArray[index] : ref largeArray[index - 5]) = 100; |
| 26 | + |
| 27 | + Console.WriteLine(string.Join(" ", smallArray)); |
| 28 | + Console.WriteLine(string.Join(" ", largeArray)); |
| 29 | + // Output: |
| 30 | + // 1 2 100 4 5 |
| 31 | + // 10 20 0 40 50 |
23 | 32 | // </SnippetConditionalRef> |
24 | 33 | } |
25 | 34 |
|
26 | | - |
27 | | - static void ConditionalValueExpressions() |
| 35 | + private static void ConditionalValueExpressions() |
28 | 36 | { |
29 | 37 | // <SnippetConditionalValue> |
30 | | - double sinc(double x) => |
31 | | - x != 0.0 ? Math.Sin(x) / x : 1.0; |
| 38 | + double sinc(double x) => x != 0.0 ? Math.Sin(x) / x : 1; |
32 | 39 |
|
33 | | - Console.WriteLine(sinc(0.2)); |
34 | 40 | Console.WriteLine(sinc(0.1)); |
35 | 41 | Console.WriteLine(sinc(0.0)); |
36 | | - /* |
37 | | - Output: |
38 | | - 0.993346653975306 |
39 | | - 0.998334166468282 |
40 | | - 1 |
41 | | - */ |
| 42 | + // Output: |
| 43 | + // 0.998334166468282 |
| 44 | + // 1 |
42 | 45 | // </SnippetConditionalValue> |
43 | 46 | } |
| 47 | + |
| 48 | + private static void ComparisonWithIf() |
| 49 | + { |
| 50 | + // <SnippetCompareWithIf> |
| 51 | + int input = new Random().Next(-5, 5); |
| 52 | + |
| 53 | + string classify; |
| 54 | + if (input >= 0) |
| 55 | + { |
| 56 | + classify = "nonnegative"; |
| 57 | + } |
| 58 | + else |
| 59 | + { |
| 60 | + classify = "negative"; |
| 61 | + } |
| 62 | + |
| 63 | + classify = (input >= 0) ? "nonnegative" : "negative"; |
| 64 | + // </SnippetCompareWithIf> |
| 65 | + } |
44 | 66 | } |
45 | 67 | } |
0 commit comments