0
0
C Sharp (C#)programming~5 mins

First, Single, and their OrDefault variants in C Sharp (C#) - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the First() method do in C#?
It returns the first element of a sequence. If the sequence is empty, it throws an exception.
Click to reveal answer
beginner
How does FirstOrDefault() differ from First()?
FirstOrDefault() returns the first element if found; otherwise, it returns the default value for the type (e.g., null for reference types, 0 for integers) instead of throwing an exception.
Click to reveal answer
intermediate
What is the key difference between Single() and First()?
Single() expects exactly one element in the sequence and throws an exception if there are zero or more than one elements. First() only requires at least one element and returns the first one.
Click to reveal answer
intermediate
When should you use SingleOrDefault()?
Use SingleOrDefault() when you expect zero or one element in the sequence. It returns the single element if found, or the default value if none are found. It throws an exception if more than one element exists.
Click to reveal answer
beginner
What happens if you call Single() on a sequence with multiple elements?
It throws an InvalidOperationException because Single() expects exactly one element, not multiple.
Click to reveal answer
What does FirstOrDefault() return if the sequence is empty?
AReturns the default value for the type
BReturns the first element
CReturns null always
DThrows an exception
Which method throws an exception if the sequence contains more than one element?
ASingle()
BFirst()
CFirstOrDefault()
DSingleOrDefault()
If you want to get the first element but avoid exceptions on empty sequences, which method should you use?
ASingle()
BFirstOrDefault()
CFirst()
DSingleOrDefault()
What will SingleOrDefault() return if the sequence has exactly one element?
AThrows an exception
BReturns default value
CReturns the single element
DReturns the first element
Which method is best when you expect exactly one element and want an exception if zero or multiple elements exist?
ASingleOrDefault()
BFirstOrDefault()
CFirst()
DSingle()
Explain the difference between First() and Single() methods in C#.
Think about how many elements each method expects and what happens if the sequence is empty or has many elements.
You got /4 concepts.
    When would you choose to use FirstOrDefault() or SingleOrDefault()?
    Consider the expected number of elements and how you want to handle empty sequences.
    You got /4 concepts.