Search code examples
c#using

C# using statement application scope


I have a question about the using statement for multiple files at once.

I have created an overload for a class that I want to use in my program. To do so in one of my files I have added the following using statement.

using ClassName = CustomClassName;

This works, but only for that particular file.

Is there a way to get this to work for my entire project?


Solution

  • This is called type aliasing, re-utilizing the using keyword may be confusing, but it is not an import.

    The purpose of this statement is to make a certain class accessible via a different name. This is useful in cases when you have different assemblies linked to your project which accidentally have classes with the same name.

    If you for instance have A.dll that defines class Foo under the A namespace, and a B.dll assembly that also defines a Foo class under the B namespace, you can use:

    using FooA = A.Foo;
    using FooB = B.Foo;
    

    to make distinctions between both.

    The scope of this is usually the current file, although, if you happen to define multiple namespaces in the same file, you can scope that to the namespace within the file:

    using FooA = A.Foo;
    
    namespace N1
    {
        // knows about FooA;
        using FooB = B.Foo;
    }
    
    namespace N2
    {
        // knows about FooA
        // does not know about FooB
    }
    

    Practically you can make this aliasing more defined but no broader than the file's scope.