Boolean Return Null

ID

csharp.boolean_return_null

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

CSharp

Tags

CWE:476, nullability, reliability

Description

Reports return null; statements inside a method whose declared return type is non-nullable bool. The non-nullable boolean type only models true and false; returning null either fails to compile or, when it sneaks through dynamic, throws NullReferenceException on the caller side.

Rationale

Tri-state booleans (true / false / unknown) are a regular cause of subtle bugs: callers expect a definite answer and have to defend against a value the type system already says cannot exist. Either commit to the binary contract or change the return type to bool? so the unknown-state is explicit.

public bool IsReady()
{
    if (something) return true;
    return null;                                 // FLAW — bool method returns null
}

public bool? MaybeReady()
{
    if (something) return true;
    return null;                                 // OK — bool? allows null
}

Remediation

Either return a concrete bool value on every code path, or change the return type to bool? to document the third state. If the absence of a value really represents an error, throw a domain exception instead of returning a sentinel.