purpose of nullable reference types introduced in c# 8.0

 

The primary purpose of nullable reference types, introduced in C# 8.0, is to help developers prevent NullReferenceException errors at compile time. They achieve this by allowing you to explicitly declare whether a reference type variable can hold a null value.

  • By default, reference types in C# prior to 8.0 were implicitly nullable. This meant you could assign null to any reference type variable without the compiler raising any warnings. This often led to runtime NullReferenceException errors when you tried to access members of a null object.
  • Nullable reference types change this default behavior. By default, reference types are now considered non-nullable. If you try to assign null to a non-nullable reference type variable without explicit null-checking, the compiler will issue a warning.
  • This allows the compiler to help you identify potential null dereference issues before your application runs, significantly improving code reliability.

 

To indicate that a reference type variable can hold a null value, you use the ? (nullable type modifier) after the type name

string name; // Non-nullable string (cannot be null without warnings) 

'string? optionalName; // Nullable string (can be null)


Related Question