C # check which integer is higher

I have two integers, int1 and int2 . I want to check which one is higher. How can I do this best? Is there a C # .NET function for this, or do I need 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 to do this?

yours, Bernhard

+4
source share
5 answers

Math.Max

Using:

 int highest = Math.Max(int1, int2); 

It is overloaded for all numeric types.

+18
source

use this:

  int result = Math.Max(int1,int2); 
+3
source

The triple operator is a bit nicer:

 return (int1 > int2) ? (int1) : (int2) ; 
+3
source
 int result = int1 > int2 ? int1 : int2; 
+1
source

If you need a more elegant way to do this, you can 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); } 

NTN

Matti

+1
source

Source: https://habr.com/ru/post/1344772/


All Articles