简体   繁体   中英

What is the practical use of arbitrary code block (by curly brackets) in C#

I have seen an example with the switch statement where each case block was surrounded by the curly brackets, like this:

switch (itemType)
{
    case ItemType.TV:
    {
        String message = Messages.GetMessage(itemType);
        Console.WriteLine(message);
        break;
    }
    case ItemType.Computer:
    {
        XPMessage message = XPMessage.Next();
        if(message.Data == "XC12")
            message.IsValid = true;

        break;
    }
    case ItemType.WashingMachine:
    {
        String message = "Washing machines are so cool.";
        Messages.SendMessage(message, itemType);
        break;
    }
    default:
    {
        break;
    }
}

The only benefit I am aware of is limiting the declaration scope (seen in the example).

However, I'd like to know if there are any other good uses for separating some parts of the code in such kind of a code block (and here I mean not neccessarily within the switch statement).

When and how do you use it, and if you don't - why don't you?

Also, is there any downside to using such blocks of code?

As you said declaration scope is one of them and also readability. Some people think it's much easier to see the braces rather than having to keep going until they see a break statement. It seems to be a personal preference. In this case it's done for scoping purposes because not all the statements use the same data type.

It's just a stylistic thing that some people prefer for readability/white space, when not done for scope purposes.

There are no additional benefits that I am aware of.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM