Using directive for nested type definitions

327 views Asked by At

I'm trying to use the using directive to define types in a functional manner to make code more readable. Let's say that my example.cs file looks like this:

using A = System.Tuple<int, int>;
using B = List<A>;

I get the error:

CS0246 The type or namespace name 'A' could not be found (are you missing a using directive or an assembly reference?)

Can I define nested types with using or is it not possible?

2

There are 2 answers

2
Rob On BEST ANSWER

The C# Language Specification on learn.microsoft.com has a section that covers the Using directive, specifically the type of using directive you're attempting to use is a "Using alias directive":

A using_alias_directive (Using alias directives) introduces an alias for a namespace or type.

The documentation highlights the permitted structure of a using_alias_directive as:

using_alias_directive
    : 'using' identifier '=' namespace_or_type_name ';'
    ;

Note that this only allows something which is a "namespace_or_type_name", but doesn't permit the use of another "using_alias_directive". One of the likely reasons for, this can be found part way through the documentation for them (emphasis mine):

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

In short, you cannot use an alias in another alias, I'm afraid.

0
Misha Zaslavsky On

In C# 12 preview it is possible to allow using alias directive to reference any kind of Type.

Beginning with C# 12, you can create aliases for types that were previously restricted, including tuple types, pointer types, and other unsafe types. For more information on the udpated rules.