The article demonstrates the use of null-state analysis to remove compiler warnings of “check code for null safety”.
Discover how to set up the nullable context in your C# project or codebase.
.NET developers often face the System.NullReferenceException, which happens when a null is referenced at runtime and results in the most common exception in the .NET application.
As the creator of null, Sir Tony Hoare, refers to null as the "billion-dollar mistake."
The variable records is set to null and then immediately referenced which results in System.NullReferenceException
TestRecord records = null;
_ = records.ToString();
record TestRecord(int Id, string Name);
As the applications grow in the number of lines of code and become more complex, spotting such issues as a developer can be challenging.
This is where C# compiler steps in.
In the previous example, a developer can avoid the System.NullReferenceExceptionby checking if the records variable was null as shown below.
TestRecord records = null;
// Check for null
if (records is not null)
{
_ = records.ToString();
}
record TestRecord(int Id, string Name);
The default value for all reference types is null.
string first; // first is null
string second = string.Empty // second is not null, instead it's an empty string ""
int third; // third is 0 because int is a value type
DateTime date; // date is DateTime.MinValue
In the example mentioned earlier:
Post C# 2.0 version, we can define nullable values using Nullable<T>. This allowed value types to be assigned with a value of null.
int? first; // first is implicitly null (uninitialized)
int? second = null; // second is explicitly null
int? third = default; // third is null as the default value for Nullable<Int32> is null
int? fourth = new(); // fourth is 0, since new calls the nullable constructor
As per my experience, this is a must-have feature that should be enabled in every .Net application as it enables control for how the compiler understands reference type variables.
There are four types of nullable contexts
it can be enabled by adding <Nullable> item to the <PropertyGroup> inside the application .csproj file as shown below
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
</PropertyGroup>
<!-- Omitted for brevity -->
</Project>
Alternatively, developers can also add scope nullable context which means the nullable context will be applicable only in the defined scope.
#nullable enable
GitHub — ssukhpinder/30DayChallenge.Net
Thank you for being a part of the C# community! Before you leave:
Follow us: X | LinkedIn | Dev.to | Hashnode | Newsletter | Tumblr
Visit our other platforms: GitHub | Instagram | Tiktok | Quora | Daily.dev
More content at C# Programming
Also published here.