#nullable enable
class TestClass {
// If we don't assign a value to _nonNullableField here or in the constructor, the compiler will warn us
string _nonNullableField;
// We don't have to supply any initial value for a nullable field, the default value of null is acceptable
string? _nullableField;
// If we don't assign a value to NonNullableProperty here or in the constructor, the compiler will warn us
public string NonNullableProperty { get; set; } = "Hello";
// We don't have to supply any initial value for a nullable property, the default value of null is acceptable
public string? NullableProperty { get; set; }
public TestClass(string? initialFieldValue) {
// If we just assign initialFieldValue to _nonNullableField without the null-coalesced fallback value, the compiler will warn us
_nonNullableField = initialFieldValue ?? "Hi";
}
public void PrintStringLengths(string nonNullableParameter, string? nullableParameter) {
Console.WriteLine($"Non-nullable parameter length is: {nonNullableParameter.Length}");
// If we don't use the null-propagation operator (?.) or check nullableParameter for null first, the compiler will warn us
Console.WriteLine($"Nullable parameter length is: {nullableParameter?.Length.ToString() ?? "<null>"}");
}
}
Code snippet taken from "Complete C# Quick Reference - C# 8".