When do you use scope without a statement in C#?

前端 未结 5 959
情深已故
情深已故 2021-01-17 07:26

Just recently I found out you can do this in C#:

{
    // google
    string url = \"#\";

    if ( value > 5 )
        url = \"http://google.com\";

    m         


        
5条回答
  •  独厮守ぢ
    2021-01-17 08:16

    {
        string f = "hello";
    }
    

    Just looks weird.

    Obviously, methods need them:

    private void hmm() {}
    

    And switch statements:

    switch(msg)
    {
        case "hi":
        // do something
        break;
    
        // ...
    }
    

    And even if, for, foreach, while statements...

    if(a == 1)
    {
        bool varIsEqual = true;
        isBusy = true;
        // do more work
    }
    

    But if you've only got 1 statement in a loop or if statement, you don't need the braces:

    if("Samantha" != "Man")
        msg = "Phew!";
    

提交回复
热议问题