views:

315

answers:

6
+3  A: 

They are not private, they are just explicitly implemented. Declaring your variables as IComparable should solve the problem:

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

    IComparable phi2 = new PersonHistoryItem(startDate, endDate);

    Assert.IsTrue(phi1.CompareTo(phi2)==0);
}
Mark Seemann
Thanks but I can't declare my variables as IComparable there. So according to your answer the other option would be to implement them implicitly, I guess. How would I do that?
Anonymous Coward
You can also just cast them in your assert statement: `Assert.IsTrue(((IComparable)phi1).CompareTo((IComparable)phi2));`
Mark Seemann
+1  A: 
var p1 = (IComparable)phi1;
var p2 = (IComparable)phi2;

Assert.IsTrue(p1.CompareTo(p2) == 0);
Darin Dimitrov
A: 

In C# an interface does not define accessors, so you can make your CompareTo method public and change the explicit interface implementation from:

int IComparable.CompareTo(object obj)

To:

public int CompareTo(object obj)
klausbyskov
A: 

Your approach uses explicit interface implementation. That means that the interface methods will not show up on your class unless a cast is done. Do this:((IComparable)phi1).CompareTo(phi2)

AZ
A: 

The main problem here is that you explicitly implements the CompareTo method, which only allows you to use it when you use your object as a IComparable object.

To correct the problem, specify the visibility as public and implement the CompareTo method not "explicitly" :

public class PersonHistoryItem : DateEntity,IComparable
{
    ...

    public int CompareTo(object obj)
    {
        PersonHistoryItem phi = (PersonHistoryItem)obj;
        return this.StartDate.CompareTo(phi.StartDate);
    }
}
Thibault Falise
A: 

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);
    }
}
Rob van Groenewoud