tabs ↹ over ␣ ␣ ␣ spaces

by Jiří {x2} Činčura

Nullable bool and if statement

16 May 2025 1 mins .NET, C#

I was writing some code in EF Core’s codebase and saw different way of writing condition on nullable bool.

The condition was written as:

if (FooBar() == true)
{
    Console.WriteLine("Test");
}
bool? FooBar() => default;

Which kind of surprised me, because I usually write it as:

if (FooBar() ?? false)
{
    Console.WriteLine("Test");
}
bool? FooBar() => default;

Both get the job done, but it got me thinking… What if one is better/faster than the other? Time to investigate.

But, both result in exactly the same IL and hence there’s no benefit of using one over the other.

using System;

if (FooBar() == true)
{
    Console.WriteLine("Test");
}
if (FooBar() ?? false)
{
    Console.WriteLine("Test");
}
bool? FooBar() => default;
[CompilerGenerated]
internal class Program
{
    private static void <Main>$(string[] args)
    {
        if (<<Main>$>g__FooBar|0_0().GetValueOrDefault())
        {
            Console.WriteLine("Test");
        }
        if (<<Main>$>g__FooBar|0_0().GetValueOrDefault())
        {
            Console.WriteLine("Test");
        }
    }

    [CompilerGenerated]
    internal static Nullable<bool> <<Main>$>g__FooBar|0_0()
    {
        return null;
    }
}

Thus, it is down to preference. And I prefer the use of null coalescing operator ?? more. Wanna prove me wrong? :-8

Profile Picture Jiří Činčura is .NET, C# and Firebird expert. He focuses on data and business layers, language constructs, parallelism, databases and performance. For almost two decades he contributes to open-source, i.e. FirebirdClient. He works as a senior software engineer for Microsoft. Frequent speaker and blogger at www.tabsoverspaces.com.