Here's a challenge to see if you do.
Below is a simple test app that creates an array of a generic type and attempts to sort it. The generic class definition is incomplete (look for the ???). Can you fill in the missing parts and avoid the error "failed to compare two elements in the array" - or indeed some other error?
(By the way, the only reason I'm posting this challenge is that this problem stumped me initially and I thought it would be good to have it documented somewhere on the internet in case others encounter similar problems).
Expand|Select|Wrap|Line Numbers
- using System;
- class Program
- {
- static void Main(string[] args)
- {
- Program.Test();
- }
- static void Test()
- {
- try
- {
- // Create an array of a generic type - MyClass<T>
- // Strongly type it to double.
- // add three elements to the array.
- MyClass<Double>[] arr = new MyClass<Double>[]
- {
- new MyClass<Double>(334.6678967),
- new MyClass<Double>(54534.6),
- new MyClass<Double>(145.4)
- };
- // View the values unsorted
- Console.WriteLine("Unsorted\n-------------");
- foreach (MyClass<Double> var in arr)
- {
- Console.WriteLine(var.ToString());
- }
- // Sort the array
- Array.Sort<MyClass<Double>>(arr);
- // View the sorted values
- Console.WriteLine("\nSorted\n-------------");
- foreach (MyClass<Double> var in arr)
- {
- Console.WriteLine(var.ToString());
- }
- Console.WriteLine("\n");
- }
- catch (InvalidOperationException ioe)
- {
- Console.Write("\nUnlucky, try again.\n\n"
- + ioe.ToString());
- }
- }
- }
- public class MyClass<T> // ??? complete the class definition here
- // to make the code compile and run.
- {
- private T _data;
- public MyClass(T data)
- { _data = data; }
- public int CompareTo( /* ??? complete the definition here */)
- { return _data.CompareTo(other._data); }
- public override string ToString()
- { return _data.ToString(); }
- }
T
p.s. I'll post the solution soon if no one else does.