1

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).

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

2
  • You could also add public override string ToString() => Message; then you could simply write if (err) { Console.WriteLine(err); } Commented Nov 16, 2024 at 15:29
  • I strongly resent your attempts to turn C# into JavaScript 😂 Commented Nov 17, 2024 at 8:15

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.