Wish u very happy new year.I have one Question about Compareto() method
of IComparable Interface.When I call Sort method of Array compareto() method of
Icomparable() interface is invoked.I want to know ,how this method compare
two objects and sort array.
I am sending code of ArraySorting, It is working with no error.
I hope you give me the answer of this question as much as possible.
using System;
namespace ArraySortingUsingIComparable
{
/// <summary>
/// Summary description for Class1.
/// </summary>
public class Name1 : IComparable
{
private string text;
public Name1(string text)
{
this.text = text;
}
public string Text
{
get
{
return text;
}
}
public int CompareTo(object obj)
{
string s1 = this.Text;
string s2 = ((Name1) obj).Text;
return String.Compare(s1, s2);
}
override public string ToString()
{
return text;
}
}
class ArrayName
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static int Main(string[] args)
{
//
// TODO: Add code to start application here
//
Name1[] array = new Name1[6];
array[0] = new Name1("Michael");
array[1] = new Name1("Charlie");
array[2] = new Name1("Peter");
array[3] = new Name1("Dana");
array[4] = new Name1("Bob");
if (array[0] is IComparable)
{
Array.Sort(array);
}
else
Console.WriteLine(
"Name does not implement IComparable");
foreach (Name1 name in array)
{
//if (name != null)
Console.WriteLine(name);
}
return 0;
}
}
}
*************************************
Bassicaly I want to know about this part of code
public string Text
{
get
{
return text;
}
}
public int CompareTo(object obj)
{
string s1 = this.Text;
string s2 = ((Name1) obj).Text;
return String.Compare(s1, s2);
}