As I understand it, in Linq the method FirstOrDefault() can return a Default value of something other than null. What I haven\'t worked out is wha
Actually, I use two approaches to avoid NullReferenceException when I'm working with collections:
public class Foo
{
public string Bar{get; set;}
}
void Main()
{
var list = new List();
//before C# 6.0
string barCSharp5 = list.DefaultIfEmpty(new Foo()).FirstOrDefault().Bar;
//C# 6.0 or later
var barCSharp6 = list.FirstOrDefault()?.Bar;
}
Use ?. or ?[ to test if is null before perform a member access Null-conditional Operators documentation
Example:
var barCSharp6 = list.FirstOrDefault()?.Bar;
Use DefaultIfEmpty() to retrieve a default value if the sequence is empty.MSDN Documentation
Example:
string barCSharp5 = list.DefaultIfEmpty(new Foo()).FirstOrDefault().Bar;