Search code examples
c#inline-if

Math.Max vs inline if - what are the differences?


I was working on a project today, and found myself using Math.Max in several places and inline if statements in other places. So, I was wondering if anybody knew which is "better"... or rather, what the real differences are.

For example, in the following, c1 = c2:

Random rand = new Random();
int a = rand.next(0,10000);
int b = rand.next(0,10000);

int c1 = Math.Max(a, b);
int c2 = a>b ? a : b;

I'm asking specifically about C#, but I suppose the answer could be different in different languages, though I'm not sure which ones have similar concepts.


Solution

  • One of the major differences I would notice right away would be for readability sake, as far as I know for implementation/performance sake, they would be nearly equivalent.

    Math.Max(a,b) is very simple to understand, regardless of previous coding knowledge.

    a>b ? a : b would require the user to have some knowledge of the ternary operator, at least.

    "When in doubt - go for readability"