Reputation: 12213
This is my abstract base class:
public abstract class BaseDataModel<T> : System.IComparable<T> where T : BaseDataModel<T>
{
public int ID { get; set; }
public int CreatedBy { get; set; }
public DateTime CreatedOn { get; set; }
public int? UpdatedBy { get; set; }
public DateTime? UpdatedOn { get; set; }
#region IComparable<T> Members
public virtual int CompareTo(T other)
{
return ID.CompareTo(other.ID);
}
#endregion
}
This class represents Person and imherits from the BaseDataModel class.
public class Person : BaseDataModel<Person>
{
public string Name { get; set; }
}
But when i am trying to sort the List using sort() method, it doesnt work. It returns the sorted list with 2 objects but all the properties in those objects are null.
static void Main(string[] args)
{
List<Person> pList = new List<Person>();
Person p = new Person();
p.ID=2;
p.Name="Z";
pList.Add(p);
Person p1 = new Person();
p.ID = 1;
p.Name = "A";
pList.Add(p1);
pList.Sort();
Console.Read();
}
}
What is the problem here?
Upvotes: 1
Views: 137
Reputation: 564641
The problem is here:
Person p = new Person();
p.ID=2;
p.Name="Z";
pList.Add(p);
Person p1 = new Person();
p.ID = 1;
p.Name = "A";
pList.Add(p1);
This should be:
Person p = new Person();
p.ID=2;
p.Name="Z";
pList.Add(p);
Person p1 = new Person();
// Change properties of p1, not p!
p1.ID = 1;
p1.Name = "A";
pList.Add(p1);
Upvotes: 2