IComaparable Interface is used to type specific comparision of objects.

IComparable.CompareTo Method compares the current instance with another object of the same type. this Function returns integer :-

int CompareTo (Object obj)

Less than zero
 
This instance is less than obj. 
Zero
 This instance is equal to obj. 
Greater than zero
 This instance is greater than obj.
 
In the following example, Version is compared with a helper class which implements Icomparable Interface.

using
System;
using System.Collections.Generic;
using System.Text;

namespace VersionCompare
{
class VersionComparision :IComparable
{
private Version currentVersion;
public VersionComparision(Version currVersion)
{
currentVersion = currVersion;
}
public int CompareTo(object compareVersion)
{
Version version = (Version)compareVersion;
if (version.Major == currentVersion.Major)
{
if (version.Minor == currentVersion.Minor)
{
if (version.Build == currentVersion.Build)
{
if (version.Revision == currentVersion.Revision)
{
return 0;
}
else if (version.Revision < currentVersion.Revision)
{
return -1;
}
else
return 1;
}
else if (version.Build < currentVersion.Build)
{
return -1;
}
else
return 1;
}
else if (version.Minor < currentVersion.Minor)
{
return -1;
}
else
return 1;
}
else if (version.Major < currentVersion.Major)
{
return -1;
}
else
return 1;
}
}
}

The following code segment find if the specified version is in the range of given versions:-

Version minVersion = new Version(1, 0, 60510, 0);
Version maxVersion = new Version(3, 0, 60530, 0);
Version currentVersion = new Version(1, 0, 60510, 0);

VersionComparision compare = new VersionComparision(currentVersion);

Response.Write(currentVersion.ToString() + "
"
);

if (compare.CompareTo(minVersion) > 0 || compare.CompareTo(maxVersion) < 0)
Response.Write( "Current Version is Out of Range");
else
Response.Write("Current Version is in the Range");

Always take the above approach when you are comparing, sorting the .Net objects. :)

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Feedback

# re: Compare .Net Versions with IComparable Interface

That was inspiring,

Nice piece of code! I learned about it and I enjoyedit

Anyway, thanks for the post 8/19/2009 12:57 PM | web development company

Post a comment





 

 

News

Employers
Soppa Group India
iSmart Panache Inc
R Systems Internationals Ltd
Technovate eSolutions Pvt Ltd
The contents of this blog are my personal opinion and do not represent in any way the view of my employer.
These postings are provided "AS IS" with no warranties, and confer no rights.

Google PR™ - Post your Page Rank with MyGooglePageRank.com

Archives

Post Categories

Image Galleries

Articles & Magazines

ASP.Net 2.0 Compilation

ASP.Net, Blogs I refer...

Atlas

Dost

Drivers and Software Download

Garhwal

Travel Domain

WSS and WebParts

Syndication: