Kornelije Petak
Kornelije Petak

Reputation: 9572

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?

Upvotes: 4

Views: 679

Answers (2)

Cortright
Cortright

Reputation: 1174

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.

Upvotes: 2

Jesus Ramos
Jesus Ramos

Reputation: 23268

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.

Upvotes: 4

Related Questions