What is the benefit of using namespace aliases? Is it good only for simplify of coding?
I use namespace aliases only if i have conflicts with classes. for me it's not simplifing at all. My opinion: if there is no need, don't use it.
I generally only use namespace aliases when using two classes with the same name.
afaik when you create namespace alias - static variables values for each alias is it's own and not depended on other aliases + simplification
They're useful when you have conflicts. For example, if you have types NamespaceA.Jobber
and NamespaceB.Jobber
, and want to use them both in the same class, you won't be able to just add using
statements for NamespaceA and NamespaceB, because then the compiler won't know what you're referring to if you type Jobber
. In this case you'd give an alias to one or both of the namespaces.
This can make your code clearer, especially if the namespace is long, because the alternative is to have the whole namespace written out each time you use a type.
Namespace alias are useful for resolving ambiguity of two or more class with the same name in your code. For example you have Button class from your winform and you also have a Button class from your 3rd library. When youur code refer to Button, you may want to quantify it to from the 3rd party and not wanting to put the full long text everywhere and rather use the alias using CompanyX = CompanyX.UI.Animated.Control
... CompanyX.Button
In fact I'm just using it earlier in a work project to also make my code more readable. I use Office Word automation and instead of having variable Application define everywhere and hard to differentiate it from my actual Application class, I define using Word=Microsoft.Office.Interop.Word
and in the code I can say Word.Application
to refer to Word application object
In cases where there are conflicting type names, using an alias will save you from having to use fully qualified names. The name TextBox
for example is used in both of the following namespaces.
System.Windows.Forms.TextBox
System.Web.UI.WebControls.TextBox
Relying on the order of the using declarations would be fairly brittle and would only help with one of the namespaces. Better would be to assign each of the namespaces an alias.
As everyone else has said, it is useful for disambiguating types when you have to import multiple namespaces at the same time.
This seems to be against other people's opinions, but it may also be useful for clarifying scope between two domains:
using Gilco.Test.ProjectX;
using DevCode = Gilco.Nilfum.Alpha.ProjectX;
public class MyTests
{
public void TestCase1()
{
var car = new DevCode.Car();
var testCar = new TestCar();
}
}
It may also be useful in the rare case when you have to specify the namespace (for disambiguation), your namespace isn't so long to justify the alias, but is likely to change soon:
using DevCode = Gilco.V1;