Situation: I have 2 classes (one base class and one derived class that inherits the base class). Both classes implement the CompareTo method, so I can sort the list.
The base class contains the following values:
day, month and year
The derived class inherits those 3 and adds 2 more:
hours and minutes
The problem is that I am adding Date and DateTime objects to the list, which it sorts correctly only on the day of the month and year.
The DateTime object that contains (day, month, year, hours, and minutes) correctly sorts the base properties when hours and minutes are not sorted at all.
But when I comment out all Date objects and add only DateTime objects, all sorting is done correctly ...
" 2 ", Virtual override calss ( CompareTo)
:
Program.cs:
List<Date> slDate = new List<Date>();
slDate.Add(new Date(1, 2, 2011));
slDate.Add(new Date(06, 01, 2000));
slDate.Add(new DateTijd(10, 11, 2011, 5, 20));
slDate.Add(new DateTijd(8, 11, 2011, 20, 01));
slDate.Add(new DateTijd(8, 11, 2011, 20, 30));
slDate.Sort();
for (int i = 0; i < slDate.Count; i++)
{
Console.WriteLine("{0}", slDate[i].ToString());
}
Date.cs( ):
public Date(int d, int m, int j)
{
}
public virtual int CompareTo(Date d)
{
int res;
res = this.Year.CompareTo(d.Year);
if (res != 0) return res;
res = this.Month.CompareTo(d.Month);
if (res != 0) return res;
res = this.Day.CompareTo(d.Day);
if (res != 0) return res;
return 0;
}
}
DateTime.cs( ):
public DateTime(int d, int m, int j, int h, int min): base(d, m, j)
{
}
class DateTime: Date
{
public override int CompareTo(Date d)
{
DateTime dt = (DateTime)d;
int res;
res = this.Hours.CompareTo(dt.Hours);
if (res != 0) return res;
res = this.Minutes.CompareTo(dt.Minutes);
if (res != 0) return res;
return 0;
}
}