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
*/
Loading
VulpesPosted Jul 30, 2013, 12:06 PM
Remember that the compiler has no idea what the actual type of the 'o' parameter is. A cast is therefore needed to tell it that 'o' refers to an Element instance.
C# is a 'statically type' language and tries to identify up as many potential errors as it can at compile time.
Posted Jul 30, 2013, 12:12 PM
Posted Jul 30, 2013, 11:47 AM
Console.WriteLine(o.GetType());
VulpesPosted Jul 30, 2013, 11:11 AM
The first thing that needs to be done within the CompareTo() method is therefore to check that 'o' does in fact refer to an Element instance (using the GetType() method). If it doesn't then an exception will be thrown on the next line anyway when you attempt to cast it to the Element type:
Element elem = (Element)o;
Posted Jul 30, 2013, 9:22 AM
VulpesPosted Jul 30, 2013, 4:33 AM
Iftikar HussainPosted Jul 30, 2013, 1:22 AM
Yes you are right, this.GetType() is type of object (the current class - Element)
Regards,
Iftikar