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();
        }
    }
}
If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

Leave a Reply


x

Interesting BlogPosts to read

How to get an Enumerator from range of elements from ArrayList in C# ?
The code snippet shown in this blog post demonstrates how you can get the enumeraor from a range of ...
How to check for the column name in an SqlDataReader Object in C# ?
When working in ADO.NET for data access , there are times when you want to check to see if a column ...
How to convert Array to List in C#?
Want to convert array of strings to List of strings in C# ? . Below is a sample code to illustrate t...