I came across following code, at first glass it does not seems to be OK but it is perfectly valid code.
static void Main(string[] args)
{
var name = "Blog"; // 1
{
var message = "Hello "; // 2
Console.WriteLine(message + name);
}
{
var message = "Good morning "; //3
Console.WriteLine(message + name);
}
}
Output
Hello Blog
Good morning Blog
Points to remember.
Here curly bracket create local scope.
It means that message variable is local to scope created by bracket.
"name" variable is global , it is accessed by child scope and value change of global variable will seen in other scope as well. ( Following is bit modified version).
static void Main(string[] args)
{
var name = "Blog"; // 1
{
var message = "Hello "; // 2
Console.WriteLine(message + name);
name = "User";
}
{
var message = "Good morning "; //3
Console.WriteLine(message + name);
}
}
Output
Hello Blog
Good morning User