Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Floating curly braces in C#

Tags:

c#

I ran across a piece of C# code today I had not seen before. The programmer defined a block of code using only curly braces (no if, class, function, etc).

{
    int i = 0;
}
i++; //compile error

Is there a purpose to this other than making the code look more organized? Is it good, bad, or whatever practice to use this "floating" contexts?

like image 316
prestomanifesto Avatar asked Aug 30 '11 16:08

prestomanifesto


People also ask

How do you write curly braces in C?

In programming, curly braces (the { and } characters) are used in a variety of ways. In C/C++, they are used to signify the start and end of a series of statements. In the following expression, everything between the { and } are executed if the variable mouseDOWNinText is true. See event loop.

Does C use curly braces?

For example, Java and C++ are often referred to as curly brace languages because curly braces are used to define the start and end of a code block.

What is the meaning of {} in Java?

In Java when you open a curly brace it means that you open a new scope (usually it's a nested scope). One important thing to understand is that a variable that you'll define inside this scope (which end where you put the closing curly brace) will not be recognized outside of the scope.

Can the curly brackets {} be used to enclose a single line of code?

90) Can the curly brackets { } be used to enclose a single line of code? While curly brackets are mainly used to group several lines of codes, it will still work without error if you used it for a single line.


2 Answers

You can use an open and close set of curly braces to define a self containing block, which has its own scope.

This is generally not considered good programming practice, though.

Usually if someone is doing something like this, it's probably better to create a method/function in its place.

like image 62
Joseph Avatar answered Oct 12 '22 00:10

Joseph


Any variable inside the "scope" of these curly braces will be out of scope outside of it.

like image 21
RBZ Avatar answered Oct 12 '22 00:10

RBZ