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. :)