CompareTo on base class not sorting children

  • Thread starter Thread starter Charlie Bear
  • Start date Start date
C

Charlie Bear

i wonder if anyone can help...

i have an abstract class called "Message" that impliment's icompareable
on the property "TimeSent".
i have two types of messages that inherit the "Message" class - Timed
Messages and Questions.
i get some of both and put them into an array list and then use the
Sort method. I need it to sort them by TimeSent regardless of type but
it groups them into questions and timedmessages. i could have sworn i
got this working at one point or maybe i just wished i had.
i thought that since they both inherit "Message" and "Message"
imliements icompareable it would sort them all as messages. the code
i'm using in "Message" is:

public int CompareTo(object obj)
{
if(obj is Message)
{
Message temp = (Message) obj;

return timeSent.CompareTo(temp.TimeSent);
}
else
{
return 0;
}
}

if anyone can help me with this i'd be grateful. cheers!
 
Hi,


Are you sure that both classes initialize the DateTime ( I assume TimeSent
is a DateTime ) , maybe one of them does not and it gets the default value.

Did you debug it , let's say an array with 4 elements, 2 of each type and
see what happen ? It should be fairly simple to follow the execution.


cheers,
 
Charlie said:
i wonder if anyone can help...

i have an abstract class called "Message" that impliment's icompareable
on the property "TimeSent".
i have two types of messages that inherit the "Message" class - Timed
Messages and Questions.
i get some of both and put them into an array list and then use the
Sort method. I need it to sort them by TimeSent regardless of type but
it groups them into questions and timedmessages. i could have sworn i
got this working at one point or maybe i just wished i had.
i thought that since they both inherit "Message" and "Message"
imliements icompareable it would sort them all as messages. the code
i'm using in "Message" is:

<snip>

Unless you're overriding CompareTo in the derived classes, that should
be working fine.

Could you post a short but complete program that demonstrates the
problem?
See http://www.pobox.com/~skeet/csharp/complete.html for what I mean by
that.

Jon
 
i built a "complete program" to send to you requested and discovered
that it works in that! i must be doing something dumb somewhere...

thanks for your help. i guess i just wanted to know if i was doing
something fundamentally wrong as i'm pretty new to OO.
 
Back
Top