I have a List<KeyValuePair<string, othertype>>. I need to do something along the lines of
list.Find(x=>x.Key=="foobar")
However, if that doesn’t exist in the list, what will the behavior be? Usually it would return null, but structs can’t be null.
It will return the
default(T)which will be the same asnew KeyValuePair<string, othertype>>(), that is, a default initialized struct.Basically, the default for reference types is always
null, and for value types (includingstruct) it’s the default (0for numerics,falseforbool, astructwith every field defaulted for structures, etc.)So, for a
default(KeyValuePair<string, othertype>>)you’d get back a KVP where theKeywasnull(default forstring) and whatever thedefault(othertype)would be (as in the examples above)…From the MSDN:
Using this, if you wanted to check and see if you got back the
default, I’d recommend checking foryourResult.Key != nullto see if you got a result, or you could use a differentFindmethod such asFindIndexas Olivier suggests.