A naive question I know and after two years of experience I am stuck to answer it.
Simply I need to create a generic method and this method may take int, double, float and compare them and find the bigger value:
object ComapreMethod(object obj1, object obj2)
{
if(obj1 > obj2)
{
return obj1;
}
return obj2;
}
I want to call it for the int,short,ushort,float,double,...etc what I am really stuck with how to compare between obj1 and obj2 I can't write it by the way above I know it is naive but I dunno it
Well, you can change your method signature using generics:
TType ComapreMethod<TType>(TType obj1, TType obj2) where TType : IComparable
and change your code in method from if(obj1>obj2)
to if (obj1.CompareTo(obj2) > 0)
(and don't forget to handle cases of obj1 and obj2 being null).
In this case you will be able to pass to your method values of some class that implemented IComparable
interface, including ints, doubles and floats.
There is a builtin solution that will do what you want, Math.Max
(MSDN docs):
var myMax = Math.Max(input1, input2);
This will work for any different types input1 and input2 that can be implicitly converted to the same type. So you can interchangeably use int
, float
and double
and it will return the appropriate value in the appropriate type (eg if passing an int and a double it will return a double)).
You could also if you wanted to just modify your method to accept doubles if you wanted to:
double CompareMethod(double obj1, double obj2)
{
if (obj1.CompareTo(obj2) > 0)
{
return obj1;
}
return obj2;
}
This again uses implicit type conversion to make ints into doubles, etc. This would mean that your return type is always a double but if you wanted to ints to return and int you can create overloads and the compiler should choose the best one.
Personally though I advise you to just use the built in
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With