I am wondering why C# allows nested/inner scopes for functions.
Here is an example of what I mean:
public int InnerScopeMethod()
{
int i = 10;
//Inner Scope
{
int j = 100;//j will not work outside of the scope.
i *= j;
}//Scope Ends Here
//j = 10 /// This Will Cause Error.
return i;
}
As you can see the method body has an anonymous or unnamed scope and it is legal in C# 4.
I want to know why is it here? Is this just for providing small scopes for variables or it has other uses?
It (usually at least) isn’t necessary to do this in C#, but then (as Brandon Moore said), why not?
One reason could be that certain variables only have a limited time where they are valid, and by putting that variable inside a scope, you make sure that noone can accidentally use them later.
Additionally, C# is based on C, where this construct is very useful. In C, variables can only be declared at the start of a scope, so something like what you wrote can be done in long methods if you only need a temporary variable at one place (ex. a loop index).