The Repeat Query Operator is one of those utilities that you’ll find very handy but can really bite you if you don’t fully realize what it’s doing. The Repeat is NOT an extension method but rather a ‘Generation Operator’. The definition indicates it creates an enumeration with a single repeated value. That could trip you up. It actually depends upon what you’re trying to repeat. For instance, if you ‘repeat’ an integer, it is new instances of integers. If you repeat an object, it is repeated references to that object. Here is a code snippet that demonstrates this:
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Text;
5:
6: namespace ConsoleApplication5
7: {
8: class Dummy
9: {
10: public int MyValue { get; set; }
11: public Dummy(int value) { MyValue = value; }
12: }
13:
14: class Program
15: {
16: static void Main(string[] args)
17: {
18: Console.WriteLine("Starting test...n");
19:
20: var listOfInts = Enumerable.Repeat(123, 2);
21:
22: // Show that the entries are actually instances and not repeated references
23: Console.WriteLine("Are the entries repeated references? {0}",
24: Object.ReferenceEquals(listOfInts.ElementAt(0), listOfInts.ElementAt(1)));
25:
26: var item = new Dummy(123);
27: var listOfObjects = Enumerable.Repeat(item, 2);
28:
29: // Show that the entries are actually repeated references to the same object.
30: Console.WriteLine("Are the entries repeated references? {0}",
31: Object.ReferenceEquals(listOfObjects.ElementAt(0), listOfObjects.ElementAt(1)));
32:
33: Console.WriteLine("nnTest is complete. Press any key to end program.");
34: Console.ReadKey();
35: }
36: }
37: }
The output of the above code is:
Starting test…
Are the entries repeated references? False
Are the entries repeated references? TrueTest is complete. Press any key to end program.
After you look at the code and consider what’s being repeated, you can understand why one is instances and the other is references. However, it has tripped up folks. More on LINQ and Lambdas to come!
Happy Coding!