Matt Hamilton
Matt Hamilton

Reputation: 204139

Why do types referenced outside of a namespace need to 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 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?

Upvotes: 8

Views: 168

Answers (3)

SLaks
SLaks

Reputation: 887453

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;

Upvotes: 4

Reed Copsey
Reed Copsey

Reputation: 564413

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".

Upvotes: 10

Chris Shain
Chris Shain

Reputation: 51329

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

Upvotes: 6

Related Questions