public class Outer
{
public class Inner
{
public static string OtherValue { get { return SomeValue; } }
}
public static string SomeValue { get { return "Outer"; } }
}
Why does the above compile? Isn’t SomeValue out of scope in Inner and need qualifying with Outer.SomeValue? Isn’t the above essentially the same as the below (which won’t compile)?
public class Outer
{
public class Inner
{
public static string OtherValue { get { return Outer.SomeValue; } }
}
public static string SomeValue { get { return "Outer"; } }
}
What static magic is going on here?
The inner class inherits part of the outer class’ scope. So members in
Outerare accessible from withinSub, but they still belong to the outer class, which is whySub.SomeValuedoes not work.The technical term is lexical scope, and it means that a variable’s scope covers the ‘lexical’ block it is in, that is, it is accessible anywhere within the source code block in which it is defined, including sub-blocks, regardless of run-time ownership. See also: https://en.wikipedia.org/wiki/Scope_%28programming%29#Lexical_scoping.
Languages like Javascript, Lisp, Haskell, and most other languages aimed at functional programming make extensive use of lexical scope, and it is closely related to other FP concepts such as partial function application, closures and currying.
Once you’ve gotten used to it, it can be an incredibly useful (and elegant) tool.