I was working on some code when I discovered something I don't fully understand so I created the following test code:
static void Main(string[] args) { string myKey = "bla"; var list = new List<KeyValuePair<string, string>>(); var list2 = new List<Test>(); var bla1 = (from a in list where a.Key == myKey select a.Value).FirstOrDefault(); var bla2 = list.FirstOrDefault(x => x.Key == myKey).Value; var bla3 = (from a in list2 where a.Key == myKey select a.Value).FirstOrDefault(); var bla4 = list2.FirstOrDefault(x => x.Key == myKey).Value; } struct Test { public string Key { get; set; } public string Value { get; set; } public Test(string key, string value) { Key = key; Value = value; } } Now as long as Test is a struct all of the 4 bla-lines work fine. But as soon as I change Test to be a class instead of a struct bla4 fails. How can this be? Isn't bla4 just another (lambda) way of doing bla3 and therefore should behave the same? Why does it make a difference whether the list contains a struct's or classes? And is there a way to have a lambda version of bla4 that doesn't throw an exception and instead returns null like the others?
?.Valueinstead of.Value?FirstOrDefault(..).Valuewill fail with a NullReferenceException