A trivial method next, with even less to talk about than "Empty"… "Repeat". This blog post is merely a matter of completeness.
What is it?
"Repeat" is a static, generic non-extension method with a single overload:
It simple returns a sequence which contains the specified element, repeated "count" times. The only argument validation is that "count" has to be non-negative.
What are we going to test?
There’s really not a lot to test here. I’ve thought of 4 different scenarios:
- A vanilla "repeat a string 3 times" sequence
- An empty sequence (repeat an element 0 times)
- A sequence containing null values (just to prove that "element" can be null)
- A negative count to prove that argument validation occurs, and does so eagerly.
None of this is remotely exciting, I’m afraid.
Let’s implement it!
Just about the only thing we could do wrong here is to put the argument validation directly in an iterator block… and we’ve implemented the "split method" pattern so many times already that we wouldn’t fall into that trap. So, here’s the code in all its tedious lack of glory:
if (count < 0)
throw new ArgumentOutOfRangeException("count");
return RepeatImpl(element, count);
private static IEnumerable<TResult> RepeatImpl<TResult>(TResult element, int count)
for (int i = 0; i < count; i++)
yield return element;
That’s it. Um, interesting points to note… none.
There’s no sense in dragging this out. That’s the lot. Next up, Count and LongCount – which actually do have a couple of interesting points.