I am missing something small here to sort an array of strings by their length using Array.Sort and IComparable<T>. The int CompareTo(string) method just won't get overloaded.
public class Program : IComparable
{
public int CompareTo(string obj)//trying to redefine CompareTo for the Array.Sort method
{
if (this.ToString().Length > obj.ToString().Length)
return 1;
if (this.ToString().Length < obj.ToString().Length)
return -1;
if (this.ToString().Length == obj.ToString().Length)
return 0;
else
throw new Exception();
}
static void Main(string[] args)
{
//to sort by length:
string[] arrayStrings = { "a", "b", "the", "roof", "is", "on", "fire" };
Array.Sort(arrayStrings);//instead comes sorted alphbetically
foreach (var item in arrayStrings)
{
Console.WriteLine(item);
}
}
}
Instead of trying to override the
CompareTomethod on thestringclass (which you can't do anyway because thestringclass is sealed), create anIComparer<string>class and pass an instance of that toArrays.Sort().Output: