So I was caught red handed using things that I admittedly didn’t know exactly what they did or what they’re supposed to be used for. In my defense, the names seemed pretty self explanatory, which I suppose lulled me into adopting the mistaken belief that I didn’t need to look up what they do.
First() is an extension method that allows you to get the first element of any collection that implements the
IEnumberable interface. When it is invoked it will either return the first element of the collection or throw an exception if the collection is empty.
FirstOrDefault() is another extension method that returns the first element of a collection that implements the
IEnumerable interface. The difference between this method and
First() is that, in the case where the collection is empty,
FirstOrDefault() returns either
null or the default value for whatever type the collection holds (i.e. 0 for integers).
When to use First() vs FirstOrDefault()
Generally, the logic should determine which one you should use… if you’re expecting the collection to always contain at least 1 element then you would most definitely want to use
First() so that an exception would get thrown if somebody messed up somewhere else in the logic and the collection is empty.
FirstOrDefault() should be used in cases where it is ‘legal’ for the collection to be empty. You can then check the return value to determine what to do from there.
tl;dr Don’t use things when you don’t know exactly what they do and what they’re supposed to be used for. Look the stuff up…
If you have any questions or suggestions of your own for print stylesheets, feel free to comment below.
BlogSlayer is the official blog of FrogSlayer, a custom software product development shop in Bryan/College Station, Texas. Our specialty is getting your product to market in 90 days or less. If you would like a free consultation for your project or big idea, email us at firstname.lastname@example.org. You can also connect with us on Twitter, Facebook, or LinkedIn.