Skip to content

Commit 327c164

Browse files
pkulikovBillWagner
authored andcommitted
Updated the conditional operator examples (#468)
1 parent b2df281 commit 327c164

File tree

1 file changed

+38
-16
lines changed

1 file changed

+38
-16
lines changed
Lines changed: 38 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,45 +1,67 @@
11
using System;
2-
using System.Collections.Generic;
3-
using System.Text;
42

53
namespace operators
64
{
75
public class ConditionalExamples
86
{
97
public static void Examples()
108
{
9+
ConditionalRefExpressions();
1110
ConditionalValueExpressions();
11+
ComparisonWithIf();
1212
}
1313

14-
static void ConditionalRefExpressions()
14+
private static void ConditionalRefExpressions()
1515
{
1616
// <SnippetConditionalRef>
1717
var smallArray = new int[] { 1, 2, 3, 4, 5 };
1818
var largeArray = new int[] { 10, 20, 30, 40, 50 };
1919

20-
int index= new Random().Next(0, 9);
20+
int index = 7;
2121
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
2332
// </SnippetConditionalRef>
2433
}
2534

26-
27-
static void ConditionalValueExpressions()
35+
private static void ConditionalValueExpressions()
2836
{
2937
// <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;
3239

33-
Console.WriteLine(sinc(0.2));
3440
Console.WriteLine(sinc(0.1));
3541
Console.WriteLine(sinc(0.0));
36-
/*
37-
Output:
38-
0.993346653975306
39-
0.998334166468282
40-
1
41-
*/
42+
// Output:
43+
// 0.998334166468282
44+
// 1
4245
// </SnippetConditionalValue>
4346
}
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+
}
4466
}
4567
}

0 commit comments

Comments
 (0)