Why should types referenced outside the namespace be fully qualified?

Given the following code snippet:

using System; using Foo = System.Int32; namespace ConsoleApplication3 { class Program { static void Main(string[] args) { } } } 

If I remove the "System". from Int32 in my declaration for an alias like "Foo", I get a compiler error. Although I use the System namespace at the top of the file, the compiler cannot find the unqualified type "Int32".

Why is this?

+8
c #
source share
3 answers

This is because the C # specification says it should be. More specifically, section 9.4.1 of the C # specification states:

The order in which the alias directives are written does not matter, and the resolution of the name or type name referenced by the using-alias directive does not depend on the using-alias directive itself or other directive directives in the directly containing compilation unit or in namespace. In other words, the namespace name or type-name of the using-alias directive is resolved as if the directly containing compilation unit or body of the namespace did not have pointer directives. However, the using-alias directive may be affected by extern-alias directives in the immediate composition of a compilation unit or namespace body.

Since the order does not matter, using System; does not affect the using-alias directive. The specific section that matters is: "the namespace name or type-name of the using-alias directive is resolved as if the directly contained compilation unit or the namespace body did not have pointer directives."

+10
source share

Because the use of operators is not processed in any particular order. The compiler does not know how to process the first line before the second.

+6
source share

spec (9.3) says:

The scope of the pointer directive extends to member-member declarations of member members of its immediate containing compilation unit or namespace body. The scope of the directive-pointer does not specifically include its instructive directives. Thus, peer-to-peer directives do not affect each other, and the order of their writing is negligible.

Transfer your last using inside the namespace block and it will work.

 using System; namespace ConsoleApplication3 { using Foo = Int32; 
+4
source share

All Articles