Namespace Alias Qualifier in C#

The Namespace in C# has the following advantages

  • It lets the developers to organise their code / classes
  • Provides a better readability of the code and helps your understand how the code structure is formed specially in bigger projects.

The Namespace Alias Qualifier in C# lets the developers to 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 also helps to avoid the ambigous 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 the Namespace1 and Namespace2 is referenced in the C# file , and trying to create an instance of Student , will cause the “Ambiguous name” error as shown in the screenshot below.

To avoid this error , we could use the :: operator to provide 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();
        }
    }
}

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...