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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With