shorthand If Statements: C#

后端 未结 4 665
隐瞒了意图╮
隐瞒了意图╮ 2020-12-14 06:06

Just a quick one, Is there anyway to shorthand this?

It\'s basically determining the direction left or right, 1 for left, 0 for right

In C#:

         


        
相关标签:
4条回答
  • 2020-12-14 06:52

    To use shorthand to get the direction:

    int direction = column == 0
                    ? 0
                    : (column == _gridSize - 1 ? 1 : rand.Next(2));
    

    To simplify the code entirely:

    if (column == gridSize - 1 || rand.Next(2) == 1)
    {
    }
    else
    {
    }
    
    0 讨论(0)
  • 2020-12-14 07:06

    Use the ternary operator

    direction == 1 ? dosomething () : dosomethingelse ();
    
    0 讨论(0)
  • 2020-12-14 07:11

    Recently, I really enjoy shorthand if else statements as a swtich case replacement. In my opinion, this is better in read and take less place. Just take a look:

    var redirectUrl =
          status == LoginStatusEnum.Success ? "/SecretPage"
        : status == LoginStatusEnum.Failure ? "/LoginFailed"
        : status == LoginStatusEnum.Sms ? "/2-StepSms"
        : status == LoginStatusEnum.EmailNotConfirmed ? "/EmailNotConfirmed"
        : "/404-Error";
    

    instead of

    string redirectUrl;
    switch (status)
    {
        case LoginStatusEnum.Success:
            redirectUrl = "/SecretPage";
            break;
        case LoginStatusEnum.Failure:
            redirectUrl = "/LoginFailed";
            break;
        case LoginStatusEnum.Sms:
            redirectUrl = "/2-StepSms";
            break;
        case LoginStatusEnum.EmailNotConfirmed:
            redirectUrl = "/EmailNotConfirmed";
            break;
        default:
            redirectUrl = "/404-Error";
            break;
    }
    
    0 讨论(0)
  • 2020-12-14 07:12

    Yes. Use the ternary operator.

    condition ? true_expression : false_expression;
    
    0 讨论(0)
提交回复
热议问题