Why does C# allow {} code blocks without a preceding statement?

后端 未结 9 2187
半阙折子戏
半阙折子戏 2020-12-14 13:48

Why does C# allow code blocks without a preceding statement (e.g. if, else, for, while)?

void Main()
{
           


        
9条回答
  •  囚心锁ツ
    2020-12-14 14:29

    You asked "why" C# allows code blocks without preceeding statements. The question "why" could also be interpreted as "what would be possible benefits of this construct?"

    Personally, I use statement-less code blocks in C# where readability is greatly improved for other developers, while keeping in mind that the code block limits the scope of local variables. For example, consider the following code snippet, which is a lot easier to read thanks to the additional code blocks:

    OrgUnit world = new OrgUnit() { Name = "World" };
    {
        OrgUnit europe = new OrgUnit() { Name = "Europe" };
        world.SubUnits.Add(europe);
        {
            OrgUnit germany = new OrgUnit() { Name = "Germany" };
            europe.SubUnits.Add(germany);
    
            //...etc.
        }
    }
    //...commit structure to DB here
    

    I'm aware that this could be solved more elegantly by using methods for each structure level. But then again, keep in mind that things like sample data seeders usually need to be quick.

    So even though the code above is executed linearly, the code structure represents the "real-world" structure of the objects, thus making it easier for other developers to understand, maintain and extend.

提交回复
热议问题