Master C# Logo banner
Welcome to MasterCSharp.com - Master C#, the easy way... - by Saurabh Nandu

 


Namespaces, using Keyword and Referencing Assemblies

Add Comment
 

 
Introduction
In this article I will explain what are Namespaces and why they should be used. Later I will explain the use of the using keyword and the need for referencing assemblies while compiling. 

Naming Problem
When a language develops, many third party components are available. All these parties try to give meaningful names to their classes like the Math class, or IntrestCalculator class etc. We as developers end up in misery due to this, just consider an example;
I am a developer who is writing up a shopping cart object. I am using third party components, now I purchase two such components, one calculates discount rates for retail customers and the other calculates discount rates for wholesale customers. The problem arises when both these components have a class called Discount. Now in my shopping cart class how do I use both these classes unambiguously?
Example:

Discount d1 = new Discount(); 
//Which component does the compiler here refer to?
//Reseller discount or Wholesaler Discount?
int discount = d1.Cal(45.78) ;


Some compilers will complain while others might just compile and use any of the components of their wish!

Solution
This problem has been identified and solved by Microsoft on the .NET Platform with the use of Namespaces. The relationship between Namespaces and classes can be directly compared to the relationship between Files and Folders on your computer. Files actually contain data, while Folders are used to just manage and logically arrange Files. Folders can also contain many files and sub folders within them. 
In the same way Classes actually contain data and Namespaces are used to logically arrange classes. Namespaces can also contain many other Namespaces and classes.
This concept may seem similar to the Package - Class relationship used in Java. But one point of caution, you DO NOT need to create folders to store classes into a Namespace. Just defining the Namespace keyword above the class definition is enough. 

But again you might say that there are 2 companies whose abbreviated names might be XYZ and if both companies develop the Discount class then, even if they used namespaces their full names would be XYZ.Discount class? Which will lead to the problem that we faced earlier! This is very true since Namespaces only help to extend the name of a class to make it unique. Hence, Microsoft is encouraging companies to use their full names to develop components and not abbreviations also if possible the departments name as well as the teams name should be used.
So say a company like American Business Company should use it full name AmericanBusinessCompany.It.DotNet.Discount instead of using ABC.Discount. This will help to solve the naming conflict.

Namespace Usage
To use namespaces all you have to do is place the namespace definition above your class definition. The dot '.' (Scope Operator) is used to denote and access classes within the namespace.
example:
Say I have a class Namer

public class Namer{
  public int i=10 ;
}


To place this class within a Namespace

namespace Saurabh.Csharp.Examples
{
  public class Namer {
    public int i=20;
  }
}


Now lets see how we will access the above two classes.

namespace Saurabh.Csharp.Examples
{
  public class NameConsumer {
    public static void Main()
    {
      Namer n1 = new Namer(); //access the plain Namer class
      Saurabh.Csharp.Examples.Namer n2 = new Saurabh.Csharp.Examples.Namer();
      System.Console.WriteLine("Just Namer value is :"+n1.i ); //This will print 10
      System.Console.WriteLine("Namespaced Namer value is :"+n2.i) ; //This will print 20
    }
  }
}


using Keyword
The using keyword can be mapped to the import keyword in Java. For people from other languages I would say simply that using keyword is used to alias a class or Namespace. All the compilers on the .NET platform emit IL (intermediate language) code on compilation, in which all the classes are referenced with their fully qualified names i.e. the full namespace as well as the class name. This would mean that developers would always have to use fully qualified names for all their classes!
 If you would see the above class NameConsumer, I have referenced all the classes using their fully qualified names, this causes a lot of typing to be done! 
In order to save the developers from typing fully qualified every time, C# has the using keyword. We use the using keyword in the beginning of the class to define some aliases to Namespaces. Then while writing our code we just refer the classes with their class name only. 
During compile time the compiler takes additional burden to try to map all the class names with the aliases that you have defined to reach at the fully qualified name of the class. Once the fully qualified name has been found it is then used to convert the code to IL code.
One important point worth mentioning is that, if you are using classes with the same names but from different Namespaces then its better to use fully qualified names in your code to refer to those classes. That is why in the above NameConsumer class where I am using two classes which have the same name Namer, I use fully qualified names to reference classes in my code.

Example
using System ;
using Saurabh.Csharp.Examples ;
public class SecondConsumer {
  public static void Main(){
    Namer n1 = new Namer();
    Console.WriteLine(n1.i) ;
  }
}


In the above code I first define some aliases using the using keyword to reference the System and Saurabh.Csharp.Examples Namespaces.
During compile time when the compiler notices a reference to the Namer class it will try to get its fully qualified name. It will first try the System.Namer combination and check the System assembly if there is any class called Namer. Since there is no such class, it will then try the Saurabh.Csharp.Examples.Namer combination, this will pass since the Namer class is contained within the Saurabh.Csharp.Examples Namespace. The compiler will then map all the references to Namer class as references to Saurabh.Csharp.Examples.Namer class in the IL code. 

You can also use the using keyword to define references to fully qualified classes with your own alias. 
example

using System ;
using MyClass = Saurabh.Csharp.Examples.Namer ; //Here we put the path up to the class ! 
public class ThirdConsumer{
  public static void Main()
  {
    MyClass mc = new MyClass(); //This actually makes a instance of the Namer class
    Console.WriteLine("The value is :"+mc.i) ;
  }
}


The above class shows how to define your own aliases. I have made a alias called MyClass to reference the class Saurabh.Csharp.Examples.Namer. Now when the compiler will reference the MyClass it will replace it with Saurabh.Csharp.Examples.Namer in the IL code. 

Referencing Assemblies
This topic does not fit here it should come under compiling, but I have placed it here to make people understand why should they reference assemblies during compilation. 
As I have explained above the using keyword is just used to provide an alias to a Namespace or a class. It actually does not import any MetaData or headers unlike C / C++ where headers used to actually be imported by placing statements like 
#include <stdio.h> 

Hence during compilation how can the compiler come to know which assemblies you have used and how can the compiler map the functions and class names ?
To enable to compiler to know where it can find the assembly which contains all the Namespaces and classes you have used, you have to reference those assemblies during compilation with the /Reference or /r compiler switch. If you fail to reference all the assemblies you have used, the compiler cannot map the classes and Namespaces and a CS0234 Error "The type or Namespace "XXX" does not exist in the class or Namespace "XXX" is raised.

So how do you know which assemblies should you reference ?
A simple way would be to look at the using keyword, check all the Namespaces you have aliased and in which assembly (library dll) does it exist. To find this out start the Reference documentation from "Start -> Program Files -> Microsoft.NET Framework SDK-> Reference Documentation".
Go to the "Reference -> Class Library" section, then check out which Namespaces what you have used. The reference documentation contains information about the assemblies/ libraries that contain the Namespace. 

Once you have figured out the list of assemblies that you have to reference, use the CSC C# compiler and while compiling add the reference to all the assemblies. 

Conclusion
This article should solve many of your doubts on what Namespaces are and why do you need to reference Dll's while compiling.

Comments

Add Comment