Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Namespace Alias Qualifier in C#

DZone's Guide to

Namespace Alias Qualifier in C#

·
Free Resource

The 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();
        }
    }
}
Topics:

Published at DZone with permission of Senthil Kumar, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}