Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Object.CompareTo()

Status
Not open for further replies.

rastam

Programmer
Nov 10, 2005
2
SE
Hi

I have an object array:

object[] a = new object[100];

the array handles int, double, strings and other types which implements IComparable. And I allways check that the objects I put in the array are of the same type, so its either all ints or string etc..

Now, what I want to do is to compare the object using CompareTo, but the compiler complains..
this is the error I get:
'object' does not contain a definition for 'CompareTo'

Is there anyway to go around this problem without Implementing the IComparable myself? Cause I know that the object I want to compare is comparable..

Hope you understand my question. Thanks in advance
 
Yes, Object does not implement IComparable, and so it doesn't have a CompareTo method.

But what you can do, if you know the object type in the array, is to cast it to the proper type, and then compare it.
Code:
Widget w = a[42] as Widget;
if (w != null)
{
   w.CompareTo(someotherwidget);
}
Chip H.


____________________________________________________________________
Donate to Katrina relief:
If you want to get the best response to a question, please read FAQ222-2244 first
 
Chip,
That looks like VB code, or is there another way to cast that I am unaware of, I thought it should be:
Code:
Widget w = (Widget)a[42];
if (w != null)
{
   w.CompareTo(someotherwidget);
}
 
The as keyword is an important, yet under-appreciated part of the C# language. It allows you to check the type of a variable without exceptions being raised or other nasty side-effects.

Chip H.


____________________________________________________________________
Donate to Katrina relief:
If you want to get the best response to a question, please read FAQ222-2244 first
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top