Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do types referenced outside of a namespace need to be fully qualified?

Tags:

c#

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 in front of Int32 in my declaration for the "Foo" type alias, I get a compiler error. Despite the fact that I'm using the System namespace at the top of the file, the compiler can't find an unqualified "Int32" type.

Why is that?

like image 610
Matt Hamilton Avatar asked Feb 04 '11 03:02

Matt Hamilton


3 Answers

This is because the C# specification says that it must be. More specifically, section 9.4.1 in the C# specification says:

The order in which using-alias-directives are written has no significance, and resolution of the namespace-or-type-name referenced by a using-alias-directive is not affected by the using-alias-directive itself or by other using-directives in the immediately containing compilation unit or namespace body. In other words, the namespace-or-type-name of a using-alias-directive is resolved as if the immediately containing compilation unit or namespace body had no using-directives. A using-alias-directive may however be affected by extern-alias-directives in the immediately containing compilation unit or namespace body.

Since order doesn't matter, the using System; has no effect on the using-alias-directive. The specific section that matters is: "the namespace-or-type-name of a using-alias-directive is resolved as if the immediately containing compilation unit or namespace body had no using-directives".

like image 89
Reed Copsey Avatar answered Nov 09 '22 00:11

Reed Copsey


Because using statements are not processed in any particular order. The compiler doesn't know to process the first line before the second.

like image 32
Chris Shain Avatar answered Nov 09 '22 00:11

Chris Shain


The spec (9.3) says:

The scope of a using-directive extends over the namespace-member-declarations of its immediately containing compilation unit or namespace body. The scope of a using-directive specifically does not include its peer using-directives. Thus, peer using-directives do not affect each other, and the order in which they are written is insignificant.

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

using System;

namespace ConsoleApplication3
{
    using Foo = Int32;
like image 35
SLaks Avatar answered Nov 09 '22 01:11

SLaks