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

前端 未结 5 910
情深已故
情深已故 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:15

    If you ask why did they implement the feature?

    I've developed my own language, and what I found was that the 'scope without a statement' syntax creeps up into grammar, very easily. It's a side-effect if you will, when writing a grammar that just works nicely & is easy to read.

    In my language, I have the same functionality, and I never "designed" for it explicitly - I got it for free. I never sat down on my desk, and thought "oh, wouldn't it be cool to have such 'feature'?". Heck - at first, I didn't even know that my grammar allowed that.

    '{}' is a "compound statement" because that simplifies the syntax for all the places you'd want to use it (conditionals, loop bodies, etc)... and because that lets you leave out the braces when a single statement is being controlled ('if (a<10) ++a;' and the like).

    The fact that it can be used anywhere a statement can appear falls directly out of that; it's harmless, and occasionally helpful as other answers have said. "If it ain't broke, don't fix it. - keshlam.

    So, the question is not so much about "why did they implement it", but rather, "why didn't they ban it / why did they allow this?"

    Could I ban this specific functionality in my language? Sure, but I see no reason to - it'll be extra cost for the company.

    Now, the above story might, or might not be true for C#, but I didn't design language (nor am I really a language designer), so it's hard to say why exactly, but thought I'd mention it anyway.

    The same functionality is in C++, which actually has some use cases - it allows a finalizer of an object to be run deterministically, if the object goes out of the scope, though this is not the case for C#.


    That said, I have not used that specific syntax in my 4 years of C# (embedded-statement -> block, when talking about concrete termins), neither I've seen it being used anywhere. Your example is begging to be refactored to methods.

    Take a look at C# grammar: http://msdn.microsoft.com/en-us/library/aa664812%28v=vs.71%29.aspx

    Also, as Jeppe has said, I've used the '{}' syntax in order to make sure that each case-block in 'switch' construction has separate local scope:

    int a = 10;
    switch(a)
    {
        case 1:
        {
            int b = 10;
            break;
        }
    
        case 2:
        {
            int b = 10;
            break;
        }
    }
    

提交回复
热议问题