Miamy
Miamy

Reputation: 2299

Access 'using' directive from different files

Consider the next solution structure:

File 1:

using MyClass = System.Collections.Generic.List<int>;

namespace NamespaceA
{
    class  A
    {
        MyClass a;
    }
}

namespace NamespaceB
{
    class B
    {
        MyClass b;
    }
}

File 2:

namespace NamespaceC
{
    class C
    {
        MyClass c; // <-- The type or namespace name 'MyClass' could not be found 
    }
}

How can I access to MyClass definition from File2? I tried to move it into NamespaceA and use using MyClass = NamespaceA.MyClass in File2, but had no success. My goal is to define complicate type in one place, not in all files where it is used.

Upvotes: 2

Views: 466

Answers (3)

Digiproc
Digiproc

Reputation: 280

In C# 10 and later, you can use a global using directive: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-directive#global-modifier

Upvotes: 1

phuzi
phuzi

Reputation: 13060

You'll have to add the using to each file you wish to use it in...

File2:

using MyClass = System.Collections.Generic.List<int>;

namespace NamespaceC
{
    class C
    {
        MyClass c; // Should work now.
    }
}

Upvotes: 1

Donut
Donut

Reputation: 112825

This is called a "using alias directive."

Per MSDN:

The scope of a using directive is limited to the file in which it appears.

There's no way do what you're trying to do; you'll have to add the alias to each file in which you wish to use it.

Upvotes: 7

Related Questions