views:

453

answers:

8

I'm working on sorting a list of objects, and unfortunately, I'm not quite getting the information from the debugging to see where I'm going wrong.

I have a custom class that I implemented a CompareTo method in, and I call .Sort() on a List of items of that class. Unfortunately, my program never actually gets to the compareTo() method...it errors out and shutdowns down immediately on the call to the .Sort().

What generally should I be on the look out for?

Here's my class definition, interface listing for the class.

    /// <summary>
/// Summary description for ClientWorkspace.
/// </summary>
public class ClientWorkspace : IStorable
{ }

I didn't list the compareTo method since it never even gets to that code.

+4  A: 

Try making your class implement the IComparable interface.

If a custom class or structure does not implement IComparable, its members cannot be ordered and the sort operation can throw an InvalidOperationException.

Source: MSDN

Matt
+1  A: 

Your class should implement IComparable or IComparable<> in order for the sort functions to know about your CompareTo() method.

David
A: 

IStorable? What's that? It's not named Sortable in .NET.

public class ClientWorkspace : IComparable<ClientWorkspace>
{ }
Mehrdad Afshari
A: 

Since you're a Java programmer you probably expect the compiler to warn you about possible exceptions that could be thrown by a particular method. Be aware that C# does NOT require you to catch any exceptions. Do this:

try {
  whatever
} catch (Exception e) {
   // put a breakpoint here and examine e.
}
eeeeaaii
Yea..That's something I'm learning as I'm learning java. :/ lol
Zack
A: 

Did you implement IComparable or IComparable<ClientWorkspace>?

As an alternative, if you don't want your class to implement that, you can also implement IComparer<ClientWorkspace> in another class, or create a method that matches the Comparer<ClientWorkspace> delegate.

.NET does not have an implicit .compareTo method.

Rob
A: 

You can implement the IComparable interface and provide an implementation of CompareTo method there. That should do it.

There's an example on MSDN.

Anna Lear
A: 

Your class needs to implement the IComparable<T> interface. See documentation on MSDN

chris166
+5  A: 

I believe the exception message would be something like this: "Failed to compare two elements in the array" with an innerexception of "At least one object must implement the IComparable interface". This gives you what you need to know:

You haven't declared your class to implement the IComparable interface.

It is not enough to just implement the CompareTo method, since the sorting algorithms will look for the IComparable interface before attempting to call CompareTo through that interface.

...and that is why your method isn't getting called.

Arjan Einbu
I figured it would be something like that. I'm getting into the CompareTo method now, so I can debug from here. Thank you.
Kivus