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
?