Home > OS >  KeyValuePair nullable problem with property
KeyValuePair nullable problem with property

Time:04-21

Code with syntax highlighting

Why does it not allow accessing the Key property, because I check in this block that kvp is not null ?

public KeyValuePair<int, int>? AddRel(int from, int to)
{
    KeyValuePair<int, int>? rel = _relations
            .Where(r => r.Key == from || r.Value == to)
            .FirstOrDefault();
    if (rel != null)
    {
        _relations.Remove(rel.Key);
    }
    _relations.Add(from, to);
    return rel;
}

CodePudding user response:

KeyValuePair is actually as struct, so KeyValuePair<TKey, TValue>? is actually Nullable<KeyValuePair<TKey, TValue>> (see Nullable struct and nullable value types doc) so you need to access Nullable.Value to get KeyValuePair:

if(rel.HasValue)
{
   var key = rel.Value.Key;
}

Note (thanks to @madreflection for reminding about that) that based on the type of _relations FirstOrDefault can behave quite differently from what you can expect cause default for value KeyValuePair<int,int> is not null:

KeyValuePair<int, int>? rel = Array.Empty<KeyValuePair<int, int>>().FirstOrDefault(); 
Console.WriteLine(rel.HasValue); // prints "True"
  • Related