Nullable Reference Types, introduced in C# 8.0, help developers avoid null reference exceptions through compile-time nullability checks, improving code quality and reducing runtime errors.
When the compiler cannot handle all cases, developers may need to use the null-forgiving operator ! to suppress warnings. This operator tells the compiler that a value will not be null, even if the compiler cannot guarantee it. However, it should be used with caution, as it can lead to runtime exceptions if the value is actually null.
Over time, as the compiler and libraries improve, the need for the null-forgiving operator may decrease. Here's an example of a useless null-forgiving operator:
C#
if (!string.IsNullOrEmpty(someString))
{
_ = someString!.Length; // null-forgiving operator is useless here
}
It's not feasible to manually navigate all code and remove the operator. Instead, you can automate the process using Roslyn and the MSBuildWorkspace (see this blog post for more details).
You can use the SuppressionCleanupTool project by Joseph Musser to scan a solution for null-forgiving operators and remove any that are unnecessary. The tool removes operators one by one and checks whether the compiler reports a new warning. If it does, the operator is kept; if not, it is removed. Simple and effective.
Shell
git clone https://github.com/jnm2/SuppressionCleanupTool.git
cd SuppressionCleanupTool
dotnet run --project src/SuppressionCleanupTool.csproj -- mysolution.sln
Depending on the size of the solution, it may take a while to complete.
Do you have a question or a suggestion about this post? Contact me!