# FirstOrDefault

In some cases, the First method may not return a result. You will most likely get an error along the lines of Sequence contains no elements. If that is the case, you can avoid this by using the FirstOrDefault method. Not only will it attempt to return the first element, but in cases where it cannot, it will return it's default 'null' value based on the type of array.

# Basic example

For instance, in an array of integers, if the First method is unable to return the first element, for whatever reason, it will return 0 as this is the default null value for an int. If it were a list of objects, the default will be null.

Here we try and find the first negative element. Since there are no negative numbers, 0 is returned as the default value.

Live example: https://dotnetfiddle.net/oSwtWo

var numbers = new[] { 2, 4, 6, 8, 10 };

int value = numbers.FirstOrDefault(n => n < 0)

//output: 0