Translated from Eric lippert's blog, original: http://blogs.msdn.com/ericlippert/archive/2009/08/03/what-s-the-difference-part-two-scope-vs-declaration-space-vs-lifetime.aspx
InProgramming LanguageScope is usually the most confusing concept in design.
People seem to use this concept inadvertently. I often see it used as a lifetime or definition space, for example, "when this variable is out of scope, the corresponding memory space will be released ". Of course, in informal occasions, as long as the audience can clearly understand what you mean, it is acceptable to use "Scope" to express it. However, in more formal scenarios, such as books or language standards, these concepts need to be used more accurately.
In C #, the difference between the scope and the definition space is subtle.
The scope of an entity isSource codeYou can use its unqualified name to reference its range.
There are some subtle things here. This definition does not have any implicit meaning -- it does not mean that if you can legally use an entity's non-qualified name, then, the entity can be referenced using this non-qualified name. Because the scope allows overlap. For exampleCode:
The scope of field x (field) is the entire definition of Class C (class) in the source code, including the entire definition of method M (method); local variable X (local variable) the scope is the main part of method M. Therefore, the scopes of these two entities overlap. When you use the non-qualified name "X" in different locations, different entities (field X or local variable X) will be obtained ).
On the contrary, a definition space is a segment that does not allow source code ranges with entities of the same name. For example, in the definition part of class C, except for the subject part of method M, other entities cannot be named as X. Once field X is defined, you cannot define other fields, properties, nested type, or event ).
The overload mechanism makes the method a little special. The space for defining methods can be defined as "Every overload method with the same name in a class constitutes an object ", you can also redefine the definition space as "entity with the same name is not allowed in the definition space, except for the method with different signatures ".
In short, the scope solves the problem of "where this name can be used", and the namespace solves the problem of "where this name is unique.
The lifetime and scope are often confused on local variables because the relationship between them is too complex. To put it simply, as long as the current execution point (point of execution) is within the scope of a local variable, it can at least ensure its content is available. However, it is also possible that the content of a local variable is out of its scope, such as capturing a variable (capture variable, variable capturing, using an external variable in an anonymous function) the lifetime of the variable will be extended.