Compare...

  • Thread starter Thread starter Jacek Jurkowski
  • Start date Start date
J

Jacek Jurkowski

Two classes:

class a
{
public DateTime MyDate
{
get{return DateTime.MinValue();}
}
}

class b
{
public DateTime MyDate
{
get{return DateTime.MaxValue();}
}
}

What do i have to do, to allow notation:
if(a < b)

instead of:
if(a.MyDate < b.MyDate) ?
 
Jacek Jurkowski said:
[...]
What do i have to do, to allow notation:
if(a < b)

instead of:
if(a.MyDate < b.MyDate) ?

Add comparison operators to either class:

class a
{
public static bool operator<(a p_a, b p_b)
{
return p_a.MyDate < p_b.MyDate;
}
public static bool operator>(a p_a, b p_b)
{
return p_a.MyDate > p_b.MyDate;
}

public DateTime MyDate
{
get { return DateTime.MinValue; }
}
}
 
Try this out
public static bool operator <(a obja, b objb)
{
return Comparison(emp1, emp2) < 0;
}

public static int Comparison(a obja, b objb)
{

if (a.MyDate < b.MyDate )

return -1

//handle other cases
}


class a
 
Jacek said:
Two classes:

class a
{
public DateTime MyDate
{
get{return DateTime.MinValue();}
}
}

class b
{
public DateTime MyDate
{
get{return DateTime.MaxValue();}
}
}

What do i have to do, to allow notation:
if(a < b)

instead of:
if(a.MyDate < b.MyDate) ?

There are two alternatives:

1. Add an implicit conversion to DateTime in each class:

public static implicit operator DateTime(a obj) {
return obj.MyDate;
}

2. Overload the operators <, >, <= and >= for combinations of a and b
objects.

If the objects contain the same type of data, perhaps you should make a
base class where you implement this.
 
Jacek said:
Two classes:

class a
{
public DateTime MyDate
{
get{return DateTime.MinValue();}
}
}

class b
{
public DateTime MyDate
{
get{return DateTime.MaxValue();}
}
}

What do i have to do, to allow notation:
if(a < b)

instead of:
if(a.MyDate < b.MyDate) ?

AFAIK you can't and it's a bit unclear to me what you are really after here. In
your example as written a and b are two different types, not two instances of
the same type. Implementing IComparable<T> in each class where <T> is the other
class would allow you to directly compare instances of your two classes.

class a : IComparable<b>
{
.. . .

public int CompareTo(b binstance)
{ return this.MyDate.CompareTo(binstance.MyDate); }

}

-rick-
 
Back
Top