Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 38 additions & 16 deletions snippets/csharp/language-reference/operators/ConditionalExamples.cs
Original file line number Diff line number Diff line change
@@ -1,45 +1,67 @@
using System;
using System.Collections.Generic;
using System.Text;

namespace operators
{
public class ConditionalExamples
{
public static void Examples()
{
ConditionalRefExpressions();
ConditionalValueExpressions();
ComparisonWithIf();
}

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

int index= new Random().Next(0, 9);
int index = 7;
ref int refValue = ref ((index < 5) ? ref smallArray[index] : ref largeArray[index - 5]);
Console.WriteLine(refValue);
refValue = 0;

index = 2;
((index < 5) ? ref smallArray[index] : ref largeArray[index - 5]) = 100;
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To show that ref in front of the conditional ref expression is not necessary.
Also, I've made the examples non-random, in order to present the output in comments. Examples with ref doesn't run in the interactive mode.


Console.WriteLine(string.Join(" ", smallArray));
Console.WriteLine(string.Join(" ", largeArray));
// Output:
// 1 2 100 4 5
// 10 20 0 40 50
// </SnippetConditionalRef>
}


static void ConditionalValueExpressions()
private static void ConditionalValueExpressions()
{
// <SnippetConditionalValue>
double sinc(double x) =>
x != 0.0 ? Math.Sin(x) / x : 1.0;
double sinc(double x) => x != 0.0 ? Math.Sin(x) / x : 1;
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor tweak to show that types might be different (double and int in this case).


Console.WriteLine(sinc(0.2));
Console.WriteLine(sinc(0.1));
Console.WriteLine(sinc(0.0));
/*
Output:
0.993346653975306
0.998334166468282
1
*/
// Output:
// 0.998334166468282
// 1
// </SnippetConditionalValue>
}

private static void ComparisonWithIf()
{
// <SnippetCompareWithIf>
int input = new Random().Next(-5, 5);

string classify;
if (input >= 0)
{
classify = "nonnegative";
}
else
{
classify = "negative";
}

classify = (input >= 0) ? "nonnegative" : "negative";
// </SnippetCompareWithIf>
}
}
}