Automating Null-Forgiving Operator Removal in C# Projects
Nullable Reference Types are a feature in C# that helps developers avoid null reference exceptions by providing compile-time checks for nullability. This feature was introduced in C# 8.0 and is designed to improve code quality and reduce runtime errors.
When the compiler cannot handle all cases, so developers may need to use the null-forgiving operator !
to suppress warnings. This operator tells the compiler that the developer is confident that a value will not be null
, even if the compiler cannot guarantee it. However, using this operator should be done with caution, as it can lead to runtime exceptions if the value is actually null
.
Over time, the compiler or the libraries may improve, and the need for the null-forgiving operator may decrease. Here's an example of useless null-forgiving operator:
if (!string.IsNullOrEmpty(someString))
{
_ = someString!.Length; // null-forgiving operator is useless here
}
It's not feasable to navigate across all code and remove the operator. Instead, you can automate the process of removing the null-forgiving operator using Roslyn and the MSBuildWorkspace
(see this blog post for more details).
You can use the project https://github.com/jnm2/SuppressionCleanupTool from Joseph Musser to check for all null-forgiving operators in a solution and remove them if they are not needed. The idea of the tool is to remove the null-forgiving operator one by one from the code and check if the compiler reports a new warning. If it does, the operator is kept. If not, the operator is removed. Simple and effective.
git clone https://github.com/jnm2/SuppressionCleanupTool.git
cd SuppressionCleanupTool
dotnet run --project src/SuppressionCleanupTool.csproj -- mysolution.sln
It can take a while to run depending on the size of the solution, so be patient.
Do you have a question or a suggestion about this post? Contact me!