Inspect type for operators and use them?

  • Thread starter Thread starter Steve
  • Start date Start date
S

Steve

Is there a way to dynamically inspect a type for the operators it
implements, and then compare two objects implementing that type?

Basically I'm looking at a situation where I receive two variables that
need to be compared, but they are boxed as type object. The only way I
have found that I can currently compare them is to use a case statement
to determine their type, cast them to the type, and then compare them.
This would be find if I only had to deal with the stock value types, but
there are custom types in the application, and that would mean writing
the necessary checks for each custom type.

Is it possible to do it all automagically?

Thanks,
Steve
 
I would take a different approach to this problem.

What you're really after, I submit, is a test to see if the items in
your list implement the IComparable interface, either as you put them
in the list, or when you're trying to compare them. (The former would
be prefereable.)

Once you know that a value or class implements IComparable, you can
call the CompareTo() method to compare them.

True, this doesn't call the operator overload methods, but then those
methods should be impelemented in terms of CompareTo(), anyway. Any
type that has comparison operators but doesn't implement IComparable
deserves a second look.

For example, I threw together this quick little application:

static void Main(string[] args)
{
int i = 5;
int j = 6;
ArrayList list = new ArrayList();
list.Add(i);
list.Add(j);
Console.WriteLine("{0} compared to {1} = {2}", list[0], list[1],
((IComparable)list[0]).CompareTo(list[1]));
}

As you can see, even boxed types compare just fine.

Now, if you need to test whether an object implements IComparable, you
can use Reflection:

Type inter = list[0].GetType().GetInterface("IComparable");
if (inter == null)
{
Console.WriteLine("Does not implement IComparable");
}
else
{
Console.WriteLine("Implements IComparable");
}


No switch statement needed!

Just for fun, I also created my own little struct (a value type) that
implements IComparable, and put it in an ArrayList (and thus boxed it).
Sure enough, I could compare the ArrayList elements like before and it
all worked.
 
Now, if you need to test whether an object implements IComparable, you
can use Reflection:

Type inter = list[0].GetType().GetInterface("IComparable");

Or just:
IComparable comp = list[0] as Comparable;
if (comp != null)
{
// supports IComparable
}

Also, to compare two objects using the default operators, use
Comparer.Default.Compare(...)
 
Back
Top