Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does nullable KeyValuePair<,> have no key property?

I have the following:

KeyValuePair<string, string>? myKVP;
// code that may conditionally do something with it
string keyString = myKVP.Key;  
// throws 'System.Nullable<System.Collections.Generic.KeyValuePair<string,string>>' 
// does not contain a definition for 'Key'

I'm sure there is some reason for this as I can see that the type is nullable. Is it because I am trying to access the key when null could cause bad things to happen?

like image 803
Matt Avatar asked May 07 '09 15:05

Matt


People also ask

What is the default value of KeyValuePair C#?

default equals to null. And default(KeyValuePair<T,U>) is an actual KeyValuePair that contains null, null .

How do you check if a key value pair exists in a dictionary C#?

Syntax: public bool ContainsKey (TKey key); Here, the key is the Key which is to be located in the Dictionary. Return Value: This method will return true if the Dictionary contains an element with the specified key otherwise, it returns false.

What is KeyValuePair C#?

The KeyValuePair class stores a pair of values in a single list with C#. Set KeyValuePair and add elements − var myList = new List<KeyValuePair<string, int>>(); // adding elements myList. Add(new KeyValuePair<string, int>("Laptop", 20)); myList.


1 Answers

Try this instead:

myKVP.Value.Key;

Here is a stripped down version of System.Nullable<T>:

public struct Nullable<T> where T: struct
{
    public T Value { get; }
}

Since the Value property is of type T you must use the Value property to get at the wrapped type instance that you are working with.

Edit: I would suggest that you check the HasValue property of your nullable type prior to using the Value.

if (myKVP.HasValue)
{
    // use myKVP.Value in here safely
}
like image 83
Andrew Hare Avatar answered Oct 14 '22 10:10

Andrew Hare