Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# help compiler to infer nullability

Conside this simple class in C# (nullability feature enabled):

public class Error
{
    public string Message = "...";

    public static implicit operator bool(Error? err) => err is not null;
}

The implicit bool operator allows me to simplify conditional checks like this:

var err = GetSomeError();

// scenario 1 (without implicit operator)
if (err is not null)
{
    Console.WriteLine(err.Message);
}

// scenario 2 (with implicit operator)
if (err)
{
    Console.WriteLine(err.Message); // <--- complains about nullability
}

However in scenario 2, the compiler doesn’t understand that err will never be null there, although the sole purpose of that implicit operator is to check for nullability, thus the execution will only get inside that if statement block when err is not null. However compiler does not recognize this and complains, forcing me to use the bang operator: err!.Message. Bang operator is not the worst solution, however, after codebase lives long enough to see several rounds of refactoring, I suddenly see redundant bang operators which wouldn’t be there if not this problem, this wouldn’t be too bad at first glance, however there’s a risk of bang operator obfuscating nullability areas (where refactoring changed the code logic).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is there any way to tell the compiler about this? Maybe via some method/class attributes, etc. ?

>Solution :

Mark the parameter with [NotNullWhen(true)], as if the conversion operator were a regular method.

public static implicit operator bool([NotNullWhen(true)] Error? err) => err is not null;

The compiler understands that when you do if(err), you are just calling the conversion operator with err as the parameter, and analyse the nullability as expected.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading