Namespace Alias Qualifier in C#
Join the DZone community and get the full member experience.
Join For Freethe namespace in c# has the following advantages
- it lets the developers organize their code / classes
- provides better readability of the code and helps you understand how the code structure is formed, especially in bigger projects.
the namespace alias qualifier in c# lets developers use the alias name instead of the complete namespace name. the advantage of the namespace alias qualifier is that it lets you use the alias name instead of a bigger namespace ( like inner namespaces ) and it also helps to avoid the ambiguous definitions of the classes.
for example
take the below class as an example
using system; using system.collections.generic; using system.linq; using system.text; using system.threading.tasks; namespace namespace1 { class student { public string studentname { get; set; } } } namespace namespace2 { class student { public string studentname { get; set; } } }
when both namespace1 and namespace2 are referenced in the c# file and are trying to create an instance of student, it will cause the “ambiguous name” error as shown in the screenshot below.
to avoid this error, we could use the :: operator to provide an alias name for the namespace and use them accordingly.
using system; using system.collections.generic; using system.linq; using system.threading.tasks; using system.windows.forms; namespace windowsformsapplication1 { using stud1 = namespace1; using stud2 = namespace2; static class program { static void main() { var obj = new stud1 :: student(); } } }
Published at DZone with permission of Senthil Kumar, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments