cs11dotnet7/vscode/Chapter06/NullHandling/Program.cs

32 lines
706 B
C#
Raw Normal View History

2022-02-27 20:08:52 +01:00
int thisCannotBeNull = 4;
//thisCannotBeNull = null; // compile error!
WriteLine(thisCannotBeNull);
int? thisCouldBeNull = null;
WriteLine(thisCouldBeNull);
WriteLine(thisCouldBeNull.GetValueOrDefault());
thisCouldBeNull = 7;
WriteLine(thisCouldBeNull);
WriteLine(thisCouldBeNull.GetValueOrDefault());
// the actual type of int? is Nullable<int>
Nullable<int> thisCouldAlsoBeNull = null;
thisCouldAlsoBeNull = 9;
WriteLine(thisCouldAlsoBeNull);
// Declaring non-nullable variables and parameters
2022-07-01 19:27:24 +02:00
Address address = new()
{
Building = null,
Street = null!, // null-forgiving operator
City = "London",
Region = "UK"
};
2022-02-27 20:08:52 +01:00
WriteLine(address.Building?.Length);
WriteLine(address.Street.Length);