Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does it mean to have a block inside my method?

Tags:

c#

.net

I previously had following code:

 public class Program
    {

        public static void Main(string[] args)
        {
              int i = 0;
           while(condition)
           {
             .........
             .........
            if (condition)           
            {
                i = 6;
                Console.WriteLine("Inside Block :" +i);
            }
           else
            {
            i = 7;
            Console.WriteLine("After block : " + i);
            }
          }
        }               
    }

Later, i figured that i don't need any conditions and want to assign 6 to variable i each time. So i commented out the code but by doing so I made a silly mistake and so now my code looks like following:

public class Program {

        public static void Main(string[] args)
        {
              int i = 0;
           while(condition)
           {
             .........
             .........
           // a block without condition                    
            {
                i = 6;
                Console.WriteLine("Inside Block :" +i);
            }

          }
        }               
    }

As you can see, by mistake i just commented out/deleted the line with if condition but forgot to remove the blocks.Now, what does this block means here. It gets executed every time which i wanted anyway but why it is not giving any error while compiling?

Do we have any terminology/concept here? I know about Initializer Block in Java but that is not what happening here. Will it work differently in Multi-Threading environment?

Any info will be really helpful.

like image 854
Harshil Doshi Avatar asked Oct 20 '25 21:10

Harshil Doshi


1 Answers

why it is not giving any error while compiling?

Do we have any terminology/concept here?

Because C# allows you to do so. C# language specification section 1.5:

A block permits multiple statements to be written in contexts where a single statement is allowed. A block consists of a list of statements written between the delimiters { and }.

So really, the if statements and while statements you are familiar with only need a single statement after their headers, and since a block is permitted wherever a single statement is permitted, you can write a block there.

And these blocks without any headers work like any other block. They create a new scope. Variables declared in the block can't be accessed outside the block.

like image 79
Sweeper Avatar answered Oct 22 '25 10:10

Sweeper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!