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

前端 未结 5 916
情深已故
情深已故 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 07:58

    That pattern has little to no effect on the runtime of C#, so it is purely an aesthetic thing (compare to C++, where we regularly use this pattern with RAII to scope things like locks).

    If I have two completely unrelated blocks of code, I will sometimes scope them this way, to make it 100% clear what variables a programmer has to keep in their head as "potentially modified in the previous block. It fills a gap between on-big-code-block and isolated functions; I can share some variables not others.

    I will also use this around auto-generated code. It can often be MUCH easier to work with such plugable-blocks without worrying about interactions.

    When I do use this, I stylistically like to put a comment before each block, roughly where an if statement would go, explaining what the block will do. I find it is helpful for avoiding other developers thinking "this looks like there used to be control flow, but somebody buggered it up." In this case, it might be a little overkill, but you'll get the idea:

    // Add a menu item for Google, if value is high enough.
    {
        string url = "#";
    
        if ( value > 5 )
            url = "http://google.com";
    
        menu.Add( new MenuItem(url) );
    }
    
    // Add a menu item for Cheese, if the value is high enough
    {
        // cheese
        string url = "#";
    
        if ( value > 45 )
            url = "http://cheese.com";
    
        menu.Add( new MenuItem(url) );
    }
    

    As stated before, this is purely stylistic in C#. Feel free to use your own style where it makes sense.

提交回复
热议问题