C# number promotion in expression
-
01-06-2021 - |
Question
I am creating a generic operator method that can dynamically compare two objects of any type. For example:
Object a = (int)5;
Object b = (long)7;
return a < b;
Now this obviously won't compile because object does not provide the less than operator. Casting the objects back to their respective types would obviously work.
However I do not know the types at runtime.
If I could use .NET 4 (which I can't) then I could cast the objects to dynamic and all would be fine. However since I cannot, I believe I'm left with codegen using expressions, or providing casts for every possible type and value!
So expressions!
If I were to create an expression, I would need to unbox the object to the correct type (easy) but then I would need to promote any numerical type to the largest of either operand. The rules for promotion are documented in the C# specification.
My question is, is there any prewritten promotion code either in the framework or not or, am I going about this the wrong way!
Thanks for the help.
Update
Thanks for the answers. I must admit I wasn't thinking of using IComparable because the method will be used for more than numbers (although I didn't explicitly mention that). Having said that, I could probably check whether or not both objects implement the interface and use it if they do.
Solution
Using generics, if you use where T : IComparable, you could use a compare method on the objects (values)
static bool IsLessThan<T>(T a, T b) where T : IComparable
{
return a.CompareTo(b) < 0;
}
For two different types:
static bool IsLessThan<T, V>(T a, V b) where T : IComparable where V : IComparable
{
return a.CompareTo(b) < 0;
}
NOTE value types int, long, etc -- already are IComparable, how cool is that? :)
OTHER TIPS
The best way would probably be to use generics (if you're not already) and constrain the generic type to those types that implement IComparable
, then use its CompareTo
method.