Maha

Maha

  • NA
  • 0
  • 309.2k

Generic

Aug 5 2013 5:00 PM
In the following program if you included a step Console.WriteLine(".." + o.GetType() + ".."); next to public int CompareTo(object o) the output saying that "o" is Element data type. Problem is highlighted.

So why it is necessary to change object data type into Element data type
(public int CompareTo(Element o)) if it is a generic class (class Element : IComparable<Element>).

using System;
public class ClassArr
{
static public void Main()
{
Element[] Arr = new Element[] { new Element(8), new Element(3), new Element(12), new Element(7) };

Array.Sort(Arr);
Console.WriteLine("Sorted:");

for (int x = 0; x < Arr.Length; ++x)
Console.WriteLine("The instance number is {0}", Arr[x].getInstance());

Console.ReadKey();
}
}
class Element : IComparable
{
int instance;

public Element(int instance)
{
this.instance = instance;
}
public int getInstance()
{
return this.instance;
}
public int CompareTo(object o)
{
Console.WriteLine(".." + o.GetType() + "..");

if (o.GetType() != this.GetType())
throw (new ArgumentException());

Element elem = (Element)o;

return (this.instance - elem.instance);
}
}

/*
Sorted:
The instance number is 3
The instance number is 7
The instance number is 8
The instance number is 12
*/


Answers (4)