I had this issue recently where I have an array of integers and I’m doing some Skip(n) and then a Take(m) on the collection. Here’s an abstraction of the code:
The output is as expected: 3, 9, 8 – skip the first three and then take the next three items.
But, what happens if I do something like:
In English – skip the first seven and the take the next 5 items from an array that contains only 10 elements. Think it’ll throw the IndexOutOfRangeException exception? Nope. These extension methods are a little smarter than that. Even though the user has requested more elements than what exists in the collection, the Take method only returns the first three thereby making the output of the program as: 7, 2, 0.
The scenario is handled similarly when you do:
This one takes the first 5 elements from the numbers array and then skips 7 of them. This is what is looks like in the debug mode: