Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

KeyValuePair nullable problem with property

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;
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading