What is the value of an anonymous unattached block in C#?

后端 未结 10 1519
谎友^
谎友^ 2021-01-11 20:43

In C# you can make a block inside of a method that is not attached to any other statement.

    public void TestMethod()
    {
        {
            string x          


        
10条回答
  •  离开以前
    2021-01-11 21:11

    This allows you to create a scope block anywhere. It's not that useful on it's own, but can make logic simpler:

    switch( value )
    {
        case const1: 
            int i = GetValueSomeHow();
            //do something
            return i.ToString();
    
        case const2:
            int i = GetADifferentValue();
            //this will throw an exception - i is already declared
     ...
    

    In C# we can use a scope block so that items declared under each case are only in scope in that case:

    switch( value )
    {
        case const1: 
        {
            int i = GetValueSomeHow();
            //do something
            return i.ToString();
        }
    
        case const2:
        {
            int i = GetADifferentValue();
            //no exception now
            return SomeFunctionOfInt( i );
        }
     ...
    

    This can also work for gotos and labels, not that you often use them in C#.

提交回复
热议问题