Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

.net - Inner/Nested Scope in Methods

I am a C# developer who has been working with the language for a long time.

I am wondering why the langauge 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?

Any Help will be appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...