GetType() and Exception is used to compare the objects. This is not a usual format. I couldn't understand this. Anyone knows explain please. Problem is highlighted.
namespace nsForEach
{
using System;
public class ClassArr
{
static public void Main()
{
clsElement[] Arr = new clsElement[]{new clsElement (8), new clsElement (3), new clsElement (12), new clsElement (7)};
Console.WriteLine("Unsorted:");
for (int x = 0; x < Arr.Length; ++x)
Console.WriteLine("The instance number is {0}", Arr[x].getInstance());
Array.Reverse(Arr);
Console.WriteLine("\r\nIn Reverse order:");
for (int x = 0; x < Arr.Length; ++x)
Console.WriteLine("The instance number is {0}", Arr[x].getInstance());
Array.Sort(Arr);
Console.WriteLine("\r\nSorted:");
for (int x = 0; x < Arr.Length; ++x)
Console.WriteLine("The instance number is {0}", Arr[x].getInstance());
Console.ReadKey();
}
}
class clsElement : IComparable
{
int instance;
public clsElement(int instance)
{
this.instance = instance;
}
public int getInstance()
{
return this.instance;
}
public int CompareTo(object o)
{
if (o.GetType() != this.GetType())
throw (new ArgumentException());
clsElement elem = (clsElement)o;
return (this.instance - elem.instance);
}
}
}
/*
Unsorted:
The instance number is 8
The instance number is 3
The instance number is 12
The instance number is 7
In Reverse order:
The instance number is 7
The instance number is 12
The instance number is 3
The instance number is 8
Sorted:
The instance number is 3
The instance number is 7
The instance number is 8
The instance number is 12
*/