The problem is that you can't use the > and < operators, because
overload selection is done at compile time, and you don't know the
types until runtime. So, operator overloading, etc, is out of the
question.
However, type coercion code is inserted at compile time, so the
convenient feature of being able to coerce int x to a decimal in order
to compare with y isn't available when you know the two types.
So, there is no out-of-the-box solution to this problem. You must write
your own run-time type checking and call the appropriate comparison
method (in the case of built-in types) and/or do smart things in the
CompareTo(object o) method for your own types.
ThunderMusic wrote:
> good idea but it does not work as "expected"...
>
> int x = 5;
> decimal y = 6;
> object obj = x;
> object obj2 = y;
> if (obj is IComparable)
> MessageBox.Show(((bool)(((IComparable)obj).CompareTo(obj2) >
> 0)).ToString());
>
> I get an ArgumentException on the last line saying the argument must be a
> System.Int32 even if an overload has an Object argument.... but doing this
> works fine :
> int x = 5;
> decimal y = 6;
> MessageBox.Show(((bool)(x > y)).ToString());
>
>
> thanks for trying... do you have another solution?
>
> ThunderMusic
>
> "Mattias Sjögren" <(E-Mail Removed)> wrote in message
> news:(E-Mail Removed)...
> >
> >>I'm doing comparisons over arguments passed as Object... they can be of
> >>any
> >>type, but must be comparable using < or >...
> >
> > Why not use the IComparable interface instead?
> >
> >
> > Mattias
> >
> > --
> > Mattias Sjögren [C# MVP] mattias @ mvps.org
> > http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
> > Please reply only to the newsgroup.