quamrana
quamrana

Reputation: 39354

Nesting aliases in C#

I've seen lots of answers to the typedef problem in C#, which I've used, so I have:

using Foo = System.Collections.Generic.Queue<Bar>;

and this works well. I can change the definition (esp. change Bar => Zoo etc) and everything that uses Foo changes. Great.

Now I want this to work:

using Foo = System.Collections.Generic.Queue<Bar>;
using FooMap = System.Collections.Generic.Dictionary<char, Foo>;

but C# doesn't seem to like Foo in the second line, even though I've defined it in the first.

Is there a way of using an existing alias as part of another?

Edit: I'm using VS2008

Upvotes: 13

Views: 1837

Answers (2)

Tobias Knauss
Tobias Knauss

Reputation: 3509

According to https://stackoverflow.com/a/35921944/2505186 this is possible when placing the
using Foo = System.Collections.Generic.Queue<Bar>;
and
using FooMap = System.Collections.Generic.Dictionary<char, Foo>;
inside different namespaces, which in your case could be

----- cs-file -----
using System; (and others if needed)

using Foo = System.Collections.Generic.Queue<Bar>;
namespace my_software
{
  using FooMap = System.Collections.Generic.Dictionary<char, Foo>;

  your usual code
}
----- file end -----

Your code would then probably be nested in an extra namepspace, which wouldn't be very nice just for this single purpose.

Upvotes: 0

Dave
Dave

Reputation: 4468

According to the standard it looks like the answer is no. From Section 16.3.1, paragraph 6:

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

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

Edit:

I just noticed that the version at the above link is a bit out of date. The text from the corresponding paragraph in the 4th Edition is more detailed, but still prohibits referencing using aliases within others. It also contains an example that makes this explicit.

Depending on your needs for scoping and strength of typing you might be able to get away with something like:

class Foo : System.Collections.Generic.Queue<Bar>
{
}

Upvotes: 15

Related Questions