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?
default equals to null. And default(KeyValuePair<T,U>) is an actual KeyValuePair that contains null, null .
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.
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With