I have 2 scenarios.
This fails:
class F<X>
{
public X X { get; set; }
}
error CS0102: The type 'F<X>
' already contains a definition for 'X
'
This works:
class F<X>
{
class G
{
public X X { get; set; }
}
}
The only logical explanation is that in the second snippet the type parameter X is out of scope, which is not true...
Why should a type parameter affect my definitions in a type?
IMO, for consistency, either both should work or neither should work.
Any other ideas?
PS: I call it 'lexical', but it is probably not the correct term.
Update:
As per Henk's answer, here is a non-generic version displaying the same behavior, but perhaps easier to grok.
Fails:
class F
{
class X { }
public X X { get; set; }
}
Works:
class X { }
class F
{
public X X { get; set; }
}
From what I can see, the C# compiler creates a lexical scope at type definition boundries.
It also implies that types and member names live in the same 'location' (or namespace
in terms of LISP).
Lexical scoping, also known as static scoping, is a convention used with many modern programming languages. It refers to setting the scope, or range of functionality, of a variable so that it may be called (referenced) from within the block of code in which it is defined.
For the purpose of their discussion, they define four (slightly different) kinds of scoping rules: trivial: no free variables allowed. static: a free variable takes its value from a set of global variables. lexical: a free variable takes the value of the binding that was in effect when the function was defined.
Lexical scope means that in a nested group of functions, the inner functions have access to the variables and other resources of their parent scope. This means that the child's functions are lexically bound to the execution context of their parents. Lexical scope is sometimes also referred to as static scope.
The scope of a formal parameter is the section of source code that can see the parameter. The scope of a formal parameter is the body of its method. For example, the scope of amount is the body of its method. The toString() method cannot see amount because it is outside the scope of amount .
The class G introduces a distinctive naming scope. If you omit the default rules, the 2 versions become:
public F<X>.X F<X>.X { get; set; } // error
public F<X>.X F<X>.G.X { get; set; } // OK
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With