Search code examples
c#switch-statementcurly-bracesparadigms

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?


Solution

  • 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.