user441521
user441521

Reputation: 6998

null-propagating operator returning bool

I have a 'Func<bool> Filter' delegate that returns a bool. However, the user of my class isn't required to supply this and if not supplied the default value should be true. If the Filter is null however, it's making result equal to false. I'm not sure why. I would think the statement would basically result in nothing happening and it remains true. What am I missing and how could I do this using this shorthand way, if possible. I know I could write this out differently but I'm trying to get the idea with this new shorthand way.

bool? result = true;
result = h.Filter?.Invoke(args);  // IF Filter IS NULL THIS LINE TURNS result TO FALSE

if (result != null || result == true)
{
    yield return h.Callback(args);

    h.Post?.Invoke(args);
}

Upvotes: 2

Views: 211

Answers (1)

ProgrammingLlama
ProgrammingLlama

Reputation: 38767

I think you've misunderstood what your code does. Specifically, your if statement.

When h.Filter is null, you are effectively assigning null to result:

bool? result = null;

Now if we were to test your "true" statement, we would see this:

Console.WriteLine("!= null: {0}", result != null); // != null: false
Console.WriteLine("== true: {0}", result == true); // == true: false

Therefore your condition is not satisfied.

It seems that what you really wanted is this (== null, rather than != null):

if (result == null || result == true)

Which can be more succinctly written as:

if (result.GetValueOrDefault(true))

Upvotes: 3

Related Questions