ar.gorgin
ar.gorgin

Reputation: 5022

How to compare values of two objects in C#

I created a struct

 public struct MyCalender : IComparable<MyCalender>
{
 public int CompareTo(PersianDate other)
    {
        return DateTime.Compare(this, other);
    }
 .
 .
 .
 .
 .
}

I new two object of this in a other UserControl, and i want compare they.

I use this code but i get error.

 MyCalender value = new MyCalender(2010,11,12);
 MyCalender value2 = new MyCalender(2010,11,12);
        if (value < value2) ==> geterror

Upvotes: 2

Views: 990

Answers (3)

Matthias Meid
Matthias Meid

Reputation: 12521

IComparable exposes CompareTo. < and > must be overloaded separately:

class Foo : IComparable<Foo>
{
    private static readonly Foo Min = new Foo(Int32.MinValue);

    private readonly int value;

    public Foo(int value)
    {
        this.value = value;
    }

    public int CompareTo(Foo other)
    {
        return this.value.CompareTo((other ?? Min).value);
    }

    public static bool operator <(Foo a, Foo b)
    {
        return (a ?? Min).CompareTo(b) < 0;
    }

    public static bool operator >(Foo a, Foo b)
    {
        return (a ?? Min).CompareTo(b) > 0;
    }
}

I edited the code so that it does not fail when comparing against null. To keep it brief I used a shortcut that works unless value is Int32.MinValue for a proper Foo. Strictly speaking you'd have to check for null explicitly to get the contract right:

By definition, any object compares greater than (or follows) null, and two null references compare equal to each other.

Besides, implementing IComparable<T> means that CompareTo(T value) takes a parameter of T. Therefore MyCalendar : IComparable<MyCalender> should implement a method CompareTo(MyCalendar other) rather than PersianDate (or implement IComparable<PersianDate>).

Upvotes: 5

Dean
Dean

Reputation: 517

if comparing just a datetime object,

would something like

  DateTime A = DateTime.Now, B = DateTime.Now.AddMinutes(1);
  var isqual = A.Date.CompareTo(B.Date);

do the trick?

or something like:

        class Calender
        {
            public DateTime datetime { get; set;}
        }

        class DateComparer : Calender, IComparable<Calender>
        {
            public int CompareTo(Calender other)
            {
                return other.datetime.Date.CompareTo(this.datetime.Date);
            }
        }

Upvotes: 0

Nikola Davidovic
Nikola Davidovic

Reputation: 8666

You should either use CompareTo method that you already implemented instead of > in the line you posted or you need to overload > and < operators for your specific class. For instance:

public static bool operator >(MyCalendar c1, MyCalendar c2)
        {
            return c1.CompareTo(c2) > 0;
        }
        public static bool operator <(MyCalendar c1, MyCalendar c2)
        {
            return c1.CompareTo(c2) < 0;
        }

But keep in mind that you have to overload both of them.

Upvotes: 0

Related Questions