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?
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".
Because using statements are not processed in any particular order. The compiler doesn't know to process the first line before the second.
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;
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