tags:

views:

849

answers:

1

Here's a simplified version of what I'm trying to do:

var days = new KeyValuePair<int, string>();
days.Add(1, "Monday");
days.Add(2, "Tuesday");
...
days.Add(7, "Sunday");

var sampleText = "My favorite day of the week is 'xyz'";
var day = days.FirstOrDefault(x => sampleText.Contains(x.Value));

Since 'xyz' is not present in the KeyValuePair variable, the FirstOrDefault method will not return a valid value. I want to be able to check for this situation but I realize that I can't compare the result to "null" because KeyValuePair is a struc. The following code is invalid:

if (day == null) {
    System.Diagnotics.Debug.Write("Couldn't find day of week");
}

We you attempt to compile the code, Visual Studio throws the following error:

Operator '==' cannot be applied to operands of type 'System.Collections.Generic.KeyValuePair<int,string>' and '<null>'

How can I check that FirstOrDefault has returned a valid value?

+15  A: 

FirstOrDefault doesn't return null, it returns default(T).
You should check for:

var defaultDay = default(KeyValuePair<int, string>);
bool b = day.Equals(defaultDay);

See also: http://msdn.microsoft.com/en-us/library/bb340482.aspx

Kobi
+1, KeyValuePair is a value type (struct), not a reference type (class) or a nullable value type, so it cannot be null.
Lucas
thanks, it workds indeed!
missing typeof operator, but still +1 for good stuff
Chris Shouts
@paper1337 - Thanks, but where am I missing `typeof`? This code compiles and works.
Kobi