5

I know default(bool?) returns null:

var msg = default(bool?) is null ? 
    "default(bool?) is NULL":                   
    "default(bool?) is NOT NULL";
// msg == "default(bool?) is NULL"

However, when dealing with a generic Type parameter, it leads to a confusing result.

Considering a generic method as below:

static TValue? GetProcItem<TValue>(IDictionary<string, JToken> cache, string key)
{
    if(cache.TryGetValue(key, out var jtoken))
    {
        var value = jtoken.ToObject<TValue>();
        return value;
    }

    // if the key does not exist
    TValue? ret = default(TValue?);  
    return ret;
}

The above code returns default(TValue?) does not work with a generic bool type specified:

var cache = new Dictionary<string, JToken>();

// the compiler infers that xBool is a boolean type instead of `bool?
var xBool = GetProcItem<bool>(cache, "a-key-that-does-not-exist"); 

// the runtime value of xBool is also a `boolean` type instead of `bool?`.
Console.WriteLine($"default(bool?)={xBool}; ");


//////////// the output is: /////////////////////////////
//////////// default(bool?)=False;

My question is : why default(bool?) returns null while a generic default(TValue?) with TValue = bool returns false?

itminus
  • 23,772
  • 2
  • 53
  • 88
  • @LegkovIvan IllusiveBrian's answer is really great. It does answer why `default(T?)` becomes `default(T)`. However, I'm still confused : if T? is same as T at runtime, why `default(bool?)` works? – itminus Mar 24 '23 at 07:13
  • 2
    @itminus Because `default(bool?)` is `default(Nullable)` – tia Mar 24 '23 at 07:25

0 Answers0