Monday 15 October 2012

.Net Tips , C# Tips : Implement IComparable interface to compare objects with C# Examples and VB.Net Examples and Sample

Click Here to Download ImplementIComparableInterface.zip

You can compare two object of same class with your predefine rules. You can also say comparison between two objects. 
You can provide compare custom types with your predefined business rules. This also allow to sort collections of instances of those types.
For comparison we implement generic System.IComparable<T> interface. For the comparison of a type based on more than one characteristic, we need to create separate types that implement the generic System.Collections.Generic.IComparer<T> interface.

If you compare two different object of same class with equal (=) operator , at that time this will check only reference location number, this will not check actual fields value property. To avoid this we need to implement IComparable interface and implements it's "CompareTo" Method.

You can call this method like this "X.CompareTo(Y)". X and Y is the object of custom class.
This method return Three possible values.

  • If X value is less than Y value, it will return less than zero (for example, -1).
  • If X value same value as Y value , it will return zero.
  • If X value is greater than Y value, It will return greater than zero (for example, 1).

Here is example for this.

In this example we take one "Books" class and make three different object of that with setting some property of that object. In this "Books" Class we implement generic "IComparable<T>" interface. And Implement "CompareTo" Method. In this method we compare property values of both object. In our example we compare that both object's "Title" property values are same or not we ignoring case sensitivity. You can also write your custom business checking rules in that method.
In this example we also check two object with equal(=) operator and You can see that you can not get your desire result.

C# Examples :
    public class Books : IComparable<Books>
    {
        public string Title { get; set; }
        public string ISBN { get; set; }
        public DateTime ReleaseDate { get; set; }
        public int Pages { get; set; }
        public int PublisherId { get; set; }

        public object Clone()
        {
            return MemberwiseClone();
        }
        public int CompareTo(Books obj)
        {
            return string.Compare(this.Title, obj.Title, true);
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        Books objBook1 = new Books { Title = "ASP.NET", ISBN = "asp1", ReleaseDate = DateTime.Parse("11/11/2010"), Pages = 200, PublisherId = 1 };
        Books objBook2 = new Books { Title = "ASP.NET1", ISBN = "asp1", ReleaseDate = DateTime.Parse("11/11/2010"), Pages = 200, PublisherId = 1 };
        Books objBook3 = new Books { Title = "ASP.NET", ISBN = "asp1", ReleaseDate = DateTime.Parse("11/11/2010"), Pages = 200, PublisherId = 1 };

        Response.Write("<br/><b>Output : </b><br/>");

        int intResult=objBook2.CompareTo(objBook1);
        if (intResult == 0)
        {
            Response.Write("<br/>objBook1 and objBook2 are same.<br/>");
        }
        else
        {
            Response.Write("<br/>objBook1 and objBook2 are not same.<br/>");
        }

        int intResult1 = objBook1.CompareTo(objBook3);
        if (intResult1 == 0)
        {
            Response.Write("<br/>objBook1 and objBook3 are same.<br/>");
        }
        else
        {
            Response.Write("<br/>objBook1 and objBook3 are not same.<br/>");
        }

        // Compare with equal operator. You can see that you can not get your desire result.
        Response.Write("<br/><b>Compare with equal operator.</b><br/>");
        if (objBook1 == objBook3)
        {
            Response.Write("<br/>objBook1 and objBook3 are same.<br/>");
        }
        else
        {
            Response.Write("<br/>objBook1 and objBook3 are not same.<br/>");
        }

    }

VB.net Examples :
    Public Class Books
        Implements IComparable(Of Books)


        Public Property Title() As String
        Public Property ISBN As String
        Public Property ReleaseDate As Date
        Public Property Pages As Integer
        Public Property PublisherId As Integer



        Public Function CompareTo(ByVal obj As Books) As Integer Implements System.IComparable(Of Books).CompareTo
            Return String.Compare(Me.Title, obj.Title, True)
        End Function

    End Class



    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim objBook1 As Books = New Books With {.Title = "ASP.NET", .ISBN = "asp1", .ReleaseDate = DateTime.Parse("11/11/2010"), .Pages = 200, .PublisherId = 1}
        Dim objBook2 As Books = New Books With {.Title = "ASP.NET1", .ISBN = "asp1", .ReleaseDate = DateTime.Parse("11/11/2010"), .Pages = 200, .PublisherId = 1}
        Dim objBook3 As Books = New Books With {.Title = "ASP.NET", .ISBN = "asp1", .ReleaseDate = DateTime.Parse("11/11/2010"), .Pages = 200, .PublisherId = 1}

        Response.Write("<br/><b>Output : </b><br/>")

        Dim intResult As Integer = objBook2.CompareTo(objBook1)
        If intResult = 0 Then
            Response.Write("<br/>objBook1 and objBook2 are same.<br/>")
        Else
            Response.Write("<br/>objBook1 and objBook2 are not same.<br/>")
        End If

        Dim intResult1 As Integer = objBook1.CompareTo(objBook3)
        If intResult1 = 0 Then
            Response.Write("<br/>objBook1 and objBook3 are same.<br/>")
        Else
            Response.Write("<br/>objBook1 and objBook3 are not same.<br/>")
        End If

        ' Compare with equal operator. You can see that you can not get your desire result.
        Response.Write("<br/><b>Compare with equal operator.</b><br/>")
        If objBook1 Is objBook3 Then
            Response.Write("<br/>objBook1 and objBook3 are same.<br/>")
        Else
            Response.Write("<br/>objBook1 and objBook3 are not same.<br/>")
        End If

    End Sub

Output : 

This article is very useful for .Net Beginners.

Note : Give Us your valuable feedback in comments. Give your suggestions in this article so we can update our articles accordingly that.




No comments:

Post a Comment