Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Nullable Explicit cast required

Tags:

c#

    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?

like image 900
bevacqua Avatar asked Feb 10 '26 08:02

bevacqua


1 Answers

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.

like image 137
Reed Copsey Avatar answered Feb 15 '26 13:02

Reed Copsey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!