forked from idg10/prog-cs-8-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
41 lines (31 loc) · 1.27 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
using System;
#nullable enable
namespace Nullability
{
class Program
{
private readonly static LegacyComponent legacy = new LegacyComponent();
static void Main()
{
string cannotBeNull = "Text";
string? mayBeNull = null;
Console.WriteLine(cannotBeNull.Length);
if (mayBeNull != null)
{
// Allowed because we can only get here if mayBeNull is not null
Console.WriteLine(mayBeNull.Length);
}
// Allowed because it checks for null and handles it
Console.WriteLine(mayBeNull?.Length ?? 0);
// The compiler will warn about this in an enabled nullable warning context
Console.WriteLine(mayBeNull.Length);
string? referenceFromLegacyComponent = legacy.GetReferenceWeKnowWontBeNull();
string nonNullableReferenceFromLegacyComponent = referenceFromLegacyComponent!;
Console.WriteLine(nonNullableReferenceFromLegacyComponent.Length);
var nullableStrings = new string?[10];
var nonNullableStrings = new string[10];
Console.WriteLine(nullableStrings[0] == null);
Console.WriteLine(nonNullableStrings[0] == null);
}
}
}