bevacqua
bevacqua

Reputation: 48476

C# Nullable Explicit cast required

    private bool? _success;
    public bool Success
    {
        get
        {
            return _success ?? (_success = false);
        }
    }

Why can't the compiler figure out the right operand is always false, and requires me to cast it to bool?

Upvotes: 2

Views: 138

Answers (3)

LWChris
LWChris

Reputation: 4201

From C# 8.0 and upwards, you can use the null-coalescing assignment operator ??=, and write most concisely:

private bool? _success;
public bool Success => _success ??= false;

The compiler will evaluate the expression as a whole and respect that the right-hand side matches the required bool type.

Upvotes: 0

Reddog
Reddog

Reputation: 15579

You would ordinarily write this using GetValueOrDefault():

private bool? _success;

public bool Success
{
    get
    {
        return _success.GetValueOrDefault(false);
    }
}

Upvotes: 0

Reed Copsey
Reed Copsey

Reputation: 564413

The right operand is a Nullable<bool> since you're assigning to bool? _success. This can't be implicitly cast to a bool, which is why the cast is required.

If you remove the assignment, then it will work fine:

return _success ?? false;

This works as the "false" is a bool already.

However, your current code returns _success after assigning it a value of false. As _success is a bool?, the right hand operand is returning bool?, and not bool.

Upvotes: 9

Related Questions