In this example we are sorting the contents in the objects referencing to the class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Apps
{
class Test1 : IComparable<Test1>
{
public int x;
public Test1(int x)
{
this.x = x;
}
public int CompareTo(Test1 other)
{
// return this.x - other.x;
return this.x.CompareTo(other.x);
}
}
class UnderstandingIcomparableInterface
{
public static void Main()
{
Test1 s1 = new Test1(110);
Test1 s2 = new Test1(40);
Test1 s3 = new Test1(90);
Test1[] s = { s1, s2,s3 }; // Abjects array
Array.Sort(s); // Sorting the objects, CompareTo method is called.
foreach (Test1 k in s)
{
Console.WriteLine(k.x);
}
}
}
}
No comments:
Post a Comment