Floating curly braces in C#

前端 未结 6 1038
执念已碎
执念已碎 2020-12-03 11:42

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

{
         


        
相关标签:
6条回答
  • 2020-12-03 11:56

    The braces {} in C# define scope. Anything defined within them goes "out of scope" once the braces are terminated.

    The example seems kind of pointless. I can't imagine why it would be used in real world code. I'm assuming you pared down the code presented?

    0 讨论(0)
  • 2020-12-03 12:05

    It limits the scope of the variable to within that block. So the variable i would not be able to be seen outside of those braces.

    It can also be a preference on if someone wants to separate code but using this when not necessary would in most cases be superfluous.

    0 讨论(0)
  • 2020-12-03 12:09

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

    0 讨论(0)
  • 2020-12-03 12:12

    There is no purpose to that code at all. Probably an artifact from something else he/she was trying to do. As the comment shows this won't even compile because i is out of scope.

    From a coding style perspective I personally don't like it and I've never seen someone use floating braces to "organize" their code before.

    0 讨论(0)
  • 2020-12-03 12:16

    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.

    0 讨论(0)
  • 2020-12-03 12:19

    The purpose of this is to illustrate that the int i is actually in a different scope than the incremented i below it.

    0 讨论(0)
提交回复
热议问题