none
Shorthand code for setting a variable based on a comparison RRS feed

  • Question

  • I have a function that accepts an integer and if that integer is higher than 100 I want to set it to 100.

    Right now, I'm doing this...

    myInt = (myInt > 100) ? 100 : myInt;

    Works great, but I was wondering if there's a shorthand way of doing the above but not setting the variable to itself if false. I just need to set the variable if > 100 is true.

    Thanks!

    And if anyone has any tips on other shorthand methods I'd love to see them.


    • Edited by T Gregory Friday, June 21, 2019 5:28 PM
    Friday, June 21, 2019 5:28 PM

Answers

  • I think that code is pretty short as is. More importantly it is an expression. Expressions must return a value. Therefore you cannot avoid returning something from that expression and since it is part of an assignment you have to assign the variable a value. So as an expression you're not going to be able to optimize that much beyond maybe using Math. You'll still have an assignment though.

    myInt = Math.Min(myInt, 100);

    Of course if you don't care about the expression then a simple if statement is just as good.

    if (myInt > 100)
       myInt = 100;


    Michael Taylor http://www.michaeltaylorp3.net

    • Marked as answer by T Gregory Monday, June 24, 2019 1:19 PM
    Friday, June 21, 2019 5:35 PM
    Moderator

All replies

  • I think that code is pretty short as is. More importantly it is an expression. Expressions must return a value. Therefore you cannot avoid returning something from that expression and since it is part of an assignment you have to assign the variable a value. So as an expression you're not going to be able to optimize that much beyond maybe using Math. You'll still have an assignment though.

    myInt = Math.Min(myInt, 100);

    Of course if you don't care about the expression then a simple if statement is just as good.

    if (myInt > 100)
       myInt = 100;


    Michael Taylor http://www.michaeltaylorp3.net

    • Marked as answer by T Gregory Monday, June 24, 2019 1:19 PM
    Friday, June 21, 2019 5:35 PM
    Moderator
  • That's what I kinda figured but I thought I'd check. Thanks!
    Friday, June 21, 2019 5:43 PM
  • Hi T Gregory,

    I want to confirm  if your question has been solved. If so, please post "Mark as answer" to the appropriate answer, so that it will help other members to find the solution quickly if they face a similar issue. If not, please feel free to let us know.

    Best Regards,

    Jack


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, June 24, 2019 2:13 AM
    Moderator