views:

348

answers:

2

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?

+12  A: 

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
}
Andrew Hare
excellent, thanks, not very intuitive is it?
Matt
It is a bit weird at first glance but once you understand how it works under the covers it makes perfect sense. :)
Andrew Hare
so i guess, the nullable has a value and that in this case the value (if it exists) is a KeyValuePair. so in this case myKVP is a nullable and its value property IS the KeyValuePair ?
Matt
Exactly! Your previous comment is 100% correct and a good way to look at it.
Andrew Hare
I actually second that this doesn't make sense - it's perfectly *logical*, but not sensible. It's pretty damned ugly in fact.
annakata
You can avoid calling .Value, .HasValue, or .GetValueOrDefault() if you supply a default value for nulls using the ?? operator. For example: KeyValuePair<string,string> foo = myNullable ?? someDefault;
Joel Mueller
A: 

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.

ra170