Maha

Maha

  • NA
  • 0
  • 325k

GetType()

Jul 29 2013 8:30 PM
Following program is simplified to focus on the problem.

Why o.GetType() is equal to this.GetType(). There may be two reasons

•Every class derives from a single class named System.Object.
•CompareTo() is within the Element class.

I wish to know whether my understanding is correct. Problem is highlighted

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)
{
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 (7)