Blog

Filter posts by Category Or Tag of the Blog section!

nullable reference types in C#

Monday, 17 June 2019

Nullable reference types in C# allow you to indicate whether a reference type (like a class or an interface) can be null or not. This feature helps you catch null reference exceptions at compile-time rather than runtime, making your code more robust and reliable. Here's a breakdown of how nullable reference types work in C#.

 

Enabling Nullable Reference Types

You can enable nullable reference types in your C# project by adding the <Nullable>enable</Nullable> element to your project file (.csproj):

 

<PropertyGroup>

  <Nullable>enable</Nullable>

</PropertyGroup>

 

Nullable Value Types

In C#, value types (like int, float, DateTime, etc.) cannot be null by default. However, with nullable value types, you can explicitly allow them to be null. You can declare a nullable value type using the? modifier:

 

int? nullableInt = null;

float? nullableFloat = 3.14f;

 

Nullable Reference Types for Classes

For reference types (classes, interfaces, delegates), you can specify if a variable can be null or not. By default, reference types are non-nullable, meaning they can't be null unless you explicitly declare them as nullable:

 

string? nullableString = null; // Nullable reference type

string nonNullableString = "Hello"; // Non-nullable reference type

 

Nullable Annotations

You can annotate your existing code to indicate nullable and non-nullable references. For example:



 

#nullable enable



string nullableString = null; // Okay, nullable reference type

string nonNullableString = "Hello"; // Okay, non-nullable reference type



#nullable disable

 

Nullable Value Coalescing

You can use the null-coalescing operator (??) to provide a default value if a nullable variable is null:

 

int? nullableNumber = null;

int result = nullableNumber ?? 10; // If nullableNumber is null, result will be 10

 

 

Nullable Reference Types and Code Analysis

When nullable reference types are enabled, the C# compiler performs static analysis to find potential null references. If you try to assign a nullable variable to a non-nullable variable without ensuring its non-null status, you'll get a compile-time warning.


 

#nullable enable



string? nullableString = "Hello";

string nonNullableString = nullableString; // Warning: nullableString may be null



#nullable disable

 

By enabling nullable reference types, you can catch potential null reference exceptions during compile-time, making your code more reliable and easier to maintain.

 

Category: Software

Tags: C#

comments powered by Disqus