If Then Else Shorthand in C#
June 29, 2007
Categories: Web & Software Development
Tags: C#
Sometimes you need to use “If Then Else” logic on something really simple, but all those brackets and parentheses are ugly and confusing. So instead use some fancy shorthand!
In this example I want to display the top 5 items in my array, but if my array is less than 5 items long I want to show all of the items up to the length of my array. (Otherwise I’d get an “index out of bounds” error for trying to access array items that don’t exist.)
int showTopeEntries = 5; showTopEntries = showTopEntries >= totalEntries ? totalEntries : showTopEntries;
This reads as: If 5 is greater than or equal to my array’s length, then use my array’s length, else use 5.
Your significant other is gonna’ be really impressed with this bit of code! Well, unless your significant other is also a programmer… then my sarcasm is lost. :/

4 Responses to “If Then Else Shorthand in C#”
By sam on May 1, 2008
What if i dont want the else?
i.e.
showTopEntries = showTopEntries >= totalEntries ? totalEntries
is there a way to get that to work?
By j on Nov 6, 2008
If you don’t want an ‘else’ in the statement, just set the ‘else’ portion to the value of the original variable. In that case, if something is true it gets set to a new value, otherwise it stays the same.
Example:
int a = 0;
int b = 10;
a = b > 100 ? b : a;
By Janus007 on Dec 23, 2008
or
showTopEntries = showTopEntries >= totalEntries ?? totalEntries
By Style on Jan 29, 2010
thanks =)