Tutorial :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?


Try this instead:


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  }  


This is because nullable types can be assigned null value or the actual value, hence you have to call ".value" on all nullable types. ".value" will return the underlying value or throw a System::InvalidOperationException.

You can also call ".HasValue" on nullable type to make sure that there is value assigned to the actual type.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »