Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"using" type alias directive doesn't work in same namespace

Tags:

c#

using

Hi I have a simple question

namespace A
{
    using TupleA = Tuple<int, int>;
    namespace B
    {       
        using DicB = Dictionary<TupleA, int>;       
    }
}    

It can be complied.. but this is not.

namespace A
{
    using TupleA = Tuple<int, int>;
    using DicB = Dictionary<TupleA, int>;               
}    

Second case, The compiler can't find the 'TupleA' type! How can I make it works? I'm using .Net Framework 4.5

like image 917
jykeith Avatar asked Oct 14 '25 12:10

jykeith


1 Answers

You cannot make the exact syntax you want work. This is because of the following passage from the C# specification (see "9.4.1 Using alias directives"):

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 C# compiler has to be able to process all of the using alias directives in a given declaration space in isolation. Because order doesn't matter, one directive cannot reference an alias in the same declaration space. Otherwise, the compiler would have to perform multiple passes through the alias directives, iteratively declaring as many as it could and trying again, until it successfully declared all aliases, or ran out of new things to declare.

As you already have seen in your own test, you can declare the alias in a declaration space containing the declaration space where you want to use it. This imposes an order to the declarations and allows the alias to be used.

like image 175
Peter Duniho Avatar answered Oct 17 '25 03:10

Peter Duniho



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!