C# 8.0: Nullable Reference Types
As we all ware of Nullable Types feature in C# also known as Nullable Value Types which was introduced since C# 2.0 version. The advantage of this type is to avoid runtime errors in case of any null value assigned to a value type parameter and using in any logic. Let’s understand in short before going further into our main topic.
In the above code, we can observe that compiler doesn’t allow non-nullable type variable to be assigned with a null value. The advantage is, such kind of issues can found at compile time.
But, what about Reference Type? Let’s take below scenario
Here, an employee is a reference type of class Employee. At line 10, we assigned a null to this reference type and immediately we are dereferencing it at line 11 to print EmpId. Surly, at runtime, it will throw a NullReferenceException exception. Our compiler doesn’t have the capability to identify such issues in advance at compile-time till now.
Such Nullable issues for reference types can be identified and mark it as Warning from C# 8.0. Yes, C# 8.0 can identify such issues and mark it as Warning. If needed, we can make it as an error by simple Visual Studio configurations.
As you can see below how Visual Studio 2019 showing it as Warning for such nullable reference types.
To avoid such reference type warnings, we need to write our logic to make sense. Following is the code modifications to above to remove such warnings from the compiler.
As we can see, when I wrote if condition to verify is employee variable is Null or not, the compiler enough intelligent now to remove the warning sign as it understands this code never execute until an employee is not null.
Note: C# 8.0 bundled with .NET Core 3.0. Still no updates from .NET Framework team to enable C# 8.0 on Framework-based applications.
To enable/disable such feature, we need to follow certain steps as below.
- Need to make sure our application created using .NET Core 3.0 and pointing to C# 8.0 (currently it is in beta when I am posting this article).
- We have two ways to enable/disable this feature. By default, it will be on disabled mode.
- Using Project File (effects Project wise): Edit .proj file and add following <NullableContextOptions> tag in first <PropertyGroup> tag.
- Using inline (effects specific block): If we don’t want to enable project level, we can enable and disable this feature for a set of code blocks using newly introduced #nullable directive as shown below
As we can see in the above code block, once we disable/restore (restore is used in case we enable anytime at a project level, it won’t disable in fact it will restore what was configured at the project level) the feature disabled and no longer can see a Warning at line 14.
This feature really useful to avoid such NullReferenceException exceptions.
Hope it helps you to understand the concept.
Happy Coding 🙂