Search code examples
c#nuniticomparable

C#: IComparable implementation private


I'm new to C# so this might be a really dump question: I implemented IComparable in my class and want to test it with NUnit. But the CompareTo-Method is marked as private and thus not accessible from the test.
What's the reason for this and how can I fix this?

The IComparable:

 
public class PersonHistoryItem : DateEntity,IComparable
    {
     ...
        int IComparable.CompareTo(object obj)
        {
            PersonHistoryItem phi = (PersonHistoryItem)obj;
            return this.StartDate.CompareTo(phi.StartDate);
        }
    }

The test:

 
        [TestMethod]
        public void TestPersonHistoryItem() {
            DateTime startDate = new DateTime(2001, 2, 2);
            DateTime endDate = new DateTime(2010, 2, 2);
            PersonHistoryItem phi1 = new PersonHistoryItem(startDate,endDate);

        PersonHistoryItem phi2 = new PersonHistoryItem(startDate, endDate);

        Assert.IsTrue(phi1.CompareTo(phi2)==0);
    }



Solution

  • I think the easiest way would be to use implicit interface implementation:

    public class PersonHistoryItem : DateEntity, IComparable
    {
        ...
        public int CompareTo(object obj)
        {
            PersonHistoryItem phi = (PersonHistoryItem)obj;
            return this.StartDate.CompareTo(phi.StartDate);
        }
    }