Time for action – getting acquainted with FirstOrDefault()

Follow the given steps:

  1. Copy the following code snippet as a query to LINQPad:
    string[] names = {};
    string defaultName = names.FirstOrDefault();
    defaultName.Dump();
  2. Run this query. You will see the following output:
    Time for action – getting acquainted with FirstOrDefault()

What just happened?

As there is no element in the array names, FirstOrDefault() puts the default value for the string (which is null) in the variable defaultName.

Last()

It's the same as First(); however, it returns the last element instead. It throws an exception if there is no element. If you want to push the default value when the collection is empty, use LastOrDefault() instead, ...

Get .NET 4.0 Generics now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.