17.12.07

Anonymous Scope Blocks

I'm picking up the habit of using anonymous scope blocks in C#--that is, braces which don't correspond to anything else:
TreeParse.Node node;
{
node = new Node(new Addition());
node.Left = new Node(new Multiplication());
node.Left.Left = new Node(new Parameter("x"));
node.Left.Right = new Node(new Number(4));
node.Right = new Node(new Number(0));
}

TreeParse.Node actual;
TreeParse.Node expected = new Node(new Multiplication());
{
expected.Left = new Node(new Parameter("x"));
expected.Right = new Node(new Number(4));

}

For this unit test, I instantiate a few trees. The nodes of the trees are instantiated and pieced together inside scope blocks. This doesn't actually affect the execution, but it keeps it cleaner and very organized.

I checked the IL and there isn't much difference. Just two nops.

Of course, you can also have actual scope benefits along with organization. Variables inside { } will be local to that block, so multiple temp variables can be created with the same name, as long as they are in different blocks.

No comments: