C# check which integer is higher
I h开发者_StackOverflow社区ave two integers, int1
and int2
. I want to check which one is the higher one. How can I do this the best? Is there an C#.NET function for this or do I have to write it myself?
Ofcource I can do something similar to this:
if (int1 < int2)
return int1;
else
return int2;
But I was wondering if there is a more elegant way for doing this?
yours, Bernhard
Math.Max
Usage:
int highest = Math.Max(int1, int2);
It's overloaded for all numeric types.
use this :
int result = Math.Max(int1,int2);
The ternary operator is a bit nicer:
return (int1 > int2) ? (int1) : (int2) ;
int result = int1 > int2 ? int1 : int2;
If you wanted a more elegant way of doing this going forward you could use method extensions. See Example below
public static int CompareTo(this int src, int compare)
{
return src == compare ? 0 : (Math.Max(src, compare) == src ? 1 : -1);
}
HTH,
Matti
精彩评论