If Then Else Shorthand in 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 showTopEntries = 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. :/

This entry was posted in Web & Software Development and tagged , . Bookmark the permalink.

16 Responses to If Then Else Shorthand in C#

  1. sam says:

    What if i dont want the else?


    showTopEntries = showTopEntries >= totalEntries ? totalEntries

    is there a way to get that to work?

  2. j says:

    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.


    int a = 0;
    int b = 10;
    a = b > 100 ? b : a;

  3. Janus007 says:

    showTopEntries = showTopEntries >= totalEntries ?? totalEntries


    • Anderlan says:

      This (“??”) is the null coalescing operator, and my VS is telling me that it does not work on a boolean on the left. This makes sense to me. What are you talking about, because I really want it to be true.

      It makes sense to have a shortcut without the else. I feel like I should use normal notation when I don’t have an else because with the condensed if/else the else statement seems like it would be performed.

      It would probably be pre-compiled out, but it still bothers me. MS, please throw in a version of this without the else just to amuse me.

      • Maybe says:

        Maybe you dont have the not-else feature because it will work in the then-else way

        int X = 8 < 0 ? 1 : 2;
        MessageBox.Show(X.ToString());// (X =2)

        (this one: int X = 8 < 0 ? 1 : X; also is pointless)

        But if you dont have an else… you will have an unasigned variable… so… am not shure how does C# handles that, but am pretty sure that makes some kind of runtime error… or at least, at the coder's logic, a very fucking bad coding practice… maybe in order to avoid that (what may or may not be a noticable mistake, depending on if you are asigning or reasigning the value of the variable) they did not added this…

        Btw thanks for the notation, as i said, i dont like to use this one… but… some times is particulary useful…

  4. Shashi says:

    It doesnt work in the followng scenario

    showtopEntries = reader[“showTopentries”] == DbNull.Value ? null : Convert.ToInt32(reader[“showTopEntries”])

    • Tyler Cash says:

      I typically do not reply to posts on any website whatsoever but your scenario may lead others to infer that the authors post is not a viable and effective option, where in fact it indeed is.
      There are a couple problems with your posted scenario:
      showtopEntries = reader[“showTopentries”] == DbNull.Value ? null : Convert.ToInt32(reader[“showTopEntries”])
      1. I am assuming that you have declared showtopEntries as an Integer as you are converting one of the conditions to an Integer. Based on that assumption, you will not be able to implicitly assign a null value to an Integer as an Integer is a value type. One could assign null to a reference type such as a string. In C# a null value is the absence of anything and therefore not a value.
      2. I realize that the author of this post has a typo within the declaration of the initial Integer, showTopeEntries where it should state showTopEntries. That said, C# is still a case sensitive language so if you mirrored the example above and remedied the typo, you will still need to ensure that the case is correct.
      If you require an Integer as the result try the following scenario: int intShowTopEntries;
      intShowTopEntries = reader[“showTopEntries”] == DbNull.Value ? 0 : Convert.ToInt32(reader[“showTopEntries”]);
      If you require for example a string as the result try the following scenario: string ShowTopEntries;
      ShowTopEntries = reader[“showTopEntries”] == DbNull.Value ? null : reader[“showTopEntries”].ToString();

  5. Ruben says:

    How can I write this shorter?
    if (min > 0)
    Data[2] = 0x00;
    else {
    Data[2] = 0x01;
    I Tried
    Data[2] = (min > 0) ? 0x00 : oxo1;

    The Data array is Byte and min is integer. It should not be a problem. but in the short form it is not working.
    Any ideas?

  6. Mike K says:

    Sashi does have a point. In the following scenario the Thing1 property is nullable, and therefore does allow a null value. The tradition if/else works here but the shorthand version will give you an error.

    public class Stuff
    public Stuff( DataRow dr )
    if( Convert.IsDBNull( dr[“thing1”] ) )
    Thing1 = null;
    Thing1 = Convert.ToInt32( dr[“thing1”] );

    Thing2 = Convert.IsDBNull( dr[“thing2”] ) ? null : dr[“thing2”].ToString();

    int? Thing1 { get; set; }
    string Thing2 { get; set; }

  7. Radu says:

    Just avoid the shorthand version as much as possible. Especially if you don’t need the else. What point is there to assign a value to its self. Avoid redundant operations and keep the code clean and easy to understand, at all times!

Leave a Reply

Your email address will not be published. Required fields are marked *