473,507 Members | 2,377 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Generics challenge!

5 New Member
Are you confident that you fully understand Generics?

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
  1.  
  2. using System;
  3.  
  4. class Program
  5. {
  6.     static void Main(string[] args)
  7.     {
  8.         Program.Test();
  9.     }
  10.  
  11.     static void Test()
  12.     {
  13.         try
  14.         {
  15.             // Create an array of a generic type - MyClass<T> 
  16.             // Strongly type it to double.
  17.             // add three elements to the array.
  18.             MyClass<Double>[] arr = new MyClass<Double>[] 
  19.                 { 
  20.                     new MyClass<Double>(334.6678967), 
  21.                     new MyClass<Double>(54534.6), 
  22.                     new MyClass<Double>(145.4) 
  23.                 };
  24.  
  25.             // View the values unsorted 
  26.             Console.WriteLine("Unsorted\n-------------");
  27.             foreach (MyClass<Double> var in arr)
  28.             {
  29.                 Console.WriteLine(var.ToString());
  30.             }
  31.  
  32.             // Sort the array
  33.             Array.Sort<MyClass<Double>>(arr);
  34.  
  35.             // View the sorted values 
  36.             Console.WriteLine("\nSorted\n-------------");
  37.             foreach (MyClass<Double> var in arr)
  38.             {
  39.                 Console.WriteLine(var.ToString());
  40.             }
  41.  
  42.             Console.WriteLine("\n");
  43.  
  44.         }
  45.         catch (InvalidOperationException ioe)
  46.         {
  47.             Console.Write("\nUnlucky, try again.\n\n" 
  48.                      + ioe.ToString());
  49.         }
  50.  
  51.     }
  52.  
  53. }
  54.  
  55. public class MyClass<T> // ??? complete the class definition here 
  56.                       // to make the code compile and run.
  57. {
  58.     private T _data;
  59.  
  60.     public MyClass(T data)
  61.     { _data = data; }
  62.  
  63.     public int CompareTo( /*  ??? complete the definition here */)
  64.     { return _data.CompareTo(other._data); }
  65.  
  66.     public override string ToString()
  67.     { return _data.ToString(); }
  68. }
  69.  
  70.  
  71.  
Good luck.
T

p.s. I'll post the solution soon if no one else does.
Nov 28 '06 #1
1 1294
tm123456789
5 New Member
Here is what the completed MyClass definition should be:

Expand|Select|Wrap|Line Numbers
  1. public class MyClass<T> : IComparable<MyClass<T>> 
  2.     where T : IComparable<T> 
  3. {
  4.     private T _data;
  5.  
  6.     public MyClass(T data)
  7.     { _data = data; }
  8.  
  9.     public int CompareTo(MyClass<T> other)
  10.     { return _data.CompareTo(other._data); }
  11.  
  12.     public override string ToString()
  13.     { return _data.ToString(); }
  14. }
  15.  
Note that MyClass must implement IComparable<MyClass<T>> in order to be able to compare two instances of itself (CompareTo is called internally by the CLR when sorting the array). Also, because the CompareTo method of an object of type T is actaully being called, T must also be constrained to implement IComparable<T> - otherwise the CompareTo method being called by _data would not be available.
Dec 3 '06 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

27
2441
by: Bernardo Heynemann | last post by:
How can I use Generics? How can I use C# 2.0? I already have VS.NET 2003 Enterprise Edition and still can´t use generics... I´m trying to make a generic collection myCollection<vartype> and...
23
2520
by: Luc Vaillant | last post by:
I need to initialise a typed parameter depending of its type in a generic class. I have tried to use the C++ template form as follow, but it doesn't work. It seems to be a limitation of generics...
12
2715
by: Michael S | last post by:
Why do people spend so much time writing complex generic types? for fun? to learn? for use? I think of generics like I do about operator overloading. Great to have as a language-feature, as...
9
5950
by: sloan | last post by:
I'm not the sharpest knife in the drawer, but not a dummy either. I'm looking for a good book which goes over Generics in great detail. and to have as a reference book on my shelf. Personal...
1
2418
by: Vladimir Shiryaev | last post by:
Hello! Exception handling in generics seems to be a bit inconsistent to me. Imagine, I have "MyOwnException" class derived from "ApplicationException". I also have two classes...
7
3242
by: SpotNet | last post by:
Hello NewsGroup, Reading up on Generics in the .NET Framework 2.0 using C# 2005 (SP1), I have a question on the application of Generics. Knowingly, Generic classes are contained in the...
2
2344
by: piter | last post by:
Hi Can generics be returned by the WebMethod? Iam thinking about <List>. Anyways where can i find list of all values that can be actually passed o returned within webservice connection? Thanks...
13
3794
by: rkausch | last post by:
Hello everyone, I'm writing because I'm frustrated with the implementation of C#'s generics, and need a workaround. I come from a Java background, and am currently writing a portion of an...
4
2009
by: =?Utf-8?B?SGF5U2VlZA==?= | last post by:
Is there some way to use Generics in dynamic code using the Type.GetType("MyClassName") as an argument? List<Type.GetType("MyClassName") oList = new List<Type.GetType("MyClassName") > ...
0
7223
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7111
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7376
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
7031
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
5623
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
3179
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1542
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
760
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
412
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.