Global Import/using Aliasing in .NET

Using import aliasing in one file/class, we can reference class library namespaces by assigning our own custom alias like this:

' VB
Imports Db = Company.Lib.Data.Objects 

// C#
using Db = Company.Lib.Data.Objects;

And then we are able to reference the classes inside of Company.Lib.Data.Objects by using the Db alias that we assigned.

Is it possible to do this at the global level so that the alias is applied to the entire solution instead of just one file/class?

Currently, we are working with web applications, so I was hoping we could add something to web.config, but I am also interested in whether or not this is possible with windows forms, console apps, and/or class libraries.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Yes this is a supported scenario in VB.Net projects. The way to do this is the following

  • Right Click on the project in Solution Explorer and select Properties
  • Go to the References tab
  • In the “Imported Namespaces” field type “Db=Company.Lib.Data.Objects”
  • Hit “Add User Import”

This will set up the alias for all files in the project.

This however does not work in C# projects. C# as a language doesn’t have the concept of a global using/import. Instead it only supports them at the file level.

Method 2

In your web.config file for your website – or most likely app.config file for a project (not confirmed)

    <pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID">
        <namespaces>
            <clear/>
            <add namespace="System"/>
            <add namespace="System.Collections"/>
            <add namespace="System.Collections.Specialized"/>
            <add namespace="System.Configuration"/>

anything that you put in this section should be a valid replacement for the Imports clause on the top of your code behind pages. Worked wonders for me, let me know if it helps you out


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x