Block of code with no syntactic meaning

sometimes I see code like below without knowing its meaning:

void myFunc() {
    MyClass a = new MyClass();

    {
        if (a.b == null) // doSomething
    }
}

      

I really like this sort of sorting and encapsulating code (not only because you can collapse the entire block at once if you don't read its contents), but I'm wondering if it has any syntactic meaning beyond optical indentation. Ofc. I know that as with every block of code, any variable declared in a block is only available there, but there are more. There are object initializers as well, but since those are about the actual instance of the class, this is a completely independent block.

+3


source to share


2 answers


Created like the one you describe

void myFunc() {
    MyClass a = new MyClass();

    {
        if (a.b == null) // doSomething
    }
}

      

Basically the same things that you like are used. Only for optical reasons and the ability to collapse these parts. They can also be used to change variable scopes, but this is less rarely used than for other purposes.

A possible alternative to this (considering only optical reasons) would be to use regions to achieve the same result. While it has the disadvantage that you have to write more than just {}, you have the advantage that you can declare WHAT as part of your code.



void myFunc() {
    MyClass a = new MyClass();

    #region Setting the players base stats
        if (a.b == null) // doSomething
    #endregion
}

      

This approach does nothing to vary the variables, but gives you at least some idea that it is not showing (if the region collapsed). Also both methods can be combined (so {} inside the scope so that you can encapsulate variables).

void myFunc() {
    MyClass a = new MyClass();

    #region Setting the players base stats
    {
        if (a.b == null) // doSomething
    }
    #endregion
}

      

But back to your question, apart from optical reasons and variable scopes, there is no syntactic reason for this.

0


source


I wonder if it has any syntactic meaning beyond optical indentation only

No, there is nothing special about them. C # declares a block as a pair of curly braces, encapsulating an optional list of operators, and notes that this allows multiple operators to be written in places where a single operator is allowed.

This, in turn, simplifies other parts of the language specification, such as if

, for

etc., which can simply be specified as if they were always followed by only one statement.



The fact that this means you can use them elsewhere as well is mostly a fluke.

You can read the full specification for these in section 8.2 C # Language Specification

+3


source







All Articles