TechyMedia

A .NET Technology blog | .NET,C# Progamming,C# tutorials,WPF WCF|Software Engineer

NAVIGATION - SEARCH

C# Namespace Alias Qualifier

Namespaces are used for logical separation of your classes and structures.In bigger projects, chances are high that same class name or structure name comes under multiple namespaces .To get rid of these ambiguity issues Namespace alias qualifier introduced in C# 2.0 which improves the readability of your code.

Namespaces are used for logical seperation of your classes and structures.In bigger projects, chances are high that same class name or structure name comes under multiple namespaces. To get rid of these ambiguity issues Namespace alias qualifier introduced in C# 2.0.

To understand the requirement of Namespace alias qualifier have a look at the code samples below.There are two different classes with same name under different namespaces.

namespace TechyMedia.Forum
{
    class Post
    {
        public void Publish()
        {
            //Useful code goes here;
        }
    }
}
 
 
namespace TechyMedia.Blog
{
    class Post
    {
        public void Publish()
        {
            //Useful code goes here;
        }
    }
} 


The 3rd class is trying to create an instance of one of the above class to access the publish method.

using TechyMedia.Blog;
using TechyMedia.Forum;

namespace Client
{
    public partial class Form1 : Form
    {              
        private void button1_Click(object sender, EventArgs e)
        {
            Post post = new Post(); //will cause compile time error
            post.Publish();
        }

    }
}


Here you will get a compile time error since the compiler will face identifying the Artice class from which namespace.This ambiguity can be rectified by using the Post class to be instatiated with its full qualified name like

TechyMedia.Blog.Post post = new TechyMedia.Blog.Post();

 
But in real life projects the namespaces,most of the time,will be longer something like "companyName.ProjctName.ModuleName.NameSpaceName" and using this full name everywhere to create instance will make code little messy.
Best solution is to use Namespace alias qualifier to replace the namespace names with aliases as below

using blog = TechyMedia.Blog;
using forum = TechyMedia.Blog;


Now you can create instance of post class like below which improves the readability of your code

blog.Post post = new blog.Post();
post.Publish();


External Assembly Alias

Pingbacks and trackbacks (1)+

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading