Practice mode C#

What is the difference between First() and FirstOrDefault() in LINQ when the sequence is empty?

Correct answer D. First() throws InvalidOperationException; FirstOrDefault() returns the type's default value

Explanation

First returns the first element and throws InvalidOperationException if the sequence, or the filtered sequence when a predicate is given, is empty. FirstOrDefault returns default(T) instead: null for reference types and 0 for int. Use First when an element must exist and FirstOrDefault when absence is normal, remembering that 0 may be ambiguous for value types.

Report a problem

Answer checked How we write and check questions

Tip: press A, B, C or D to answer, and N for the next question.

Advertisement

Have a question about this answer?

Your email address will not be published. Required fields are marked *

Links and website addresses are not allowed in comments.