Enumerable's LastOrDefault Method

It's actually quite common to want to get the last item out of a list or an array. One way to do this might be this:

object last = values[values.Length - 1];

That's a common programming idiom, and most experienced programmers will recognize it as the pattern for getting the last item in the list. (C# arrays and lists all use zero-based indexing, so there's a -1 in there for that.)

Of course, it gets more complicated when it's possible the list will be empty. That code turns into this:

object last = null;
if(values.Length > 0)
    last = values[values.Length - 1];

And of course, in practice, there's always the possibility that it's empty. So it's something you need to account for.

Instead of all of that, try this instead:

object last = values.LastOrDefault();

This will return the last item in the list, or the default value for the type if it's empty. (For reference types, the default value is null. For value types, like most of the built-in types, this is 0, or whatever would most closely amount to 0 (like false and the null terminator character ('\0') for the char type.)

The LastOrDefault method is actually on the Enumerable type, so basically anything that contains more than one item (including the List type and arrays, but also a whole lot of other types) will have it.

And for what it's worth, it's actually an extension method. So there's another example of how those things get used in the Base Class Library.