Namespaces
Namespaces are basically used to organize our code and to differentiate between the classes or methods with the same name. There are three ways to use namespaces.
- Using directives
- Using fully qualified name
- Using alias for namespaces
Using DirectivesFor invoking the method from class A, we are using directive for declaring the namespace, as shown below.
- using project2;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using NameSpace1;
-
- namespace ConsoleApplication1
- {
- class Program
- {
- static void Main(string[] args)
- {
- A a = new A();
- a.classAMethod();
- }
- }
- }
-
- namespace NameSpace1
- {
- namespace namespaceForClass1
- {
- public class A
- {
- public void classAMethod()
- {
- Console.WriteLine("I am method from Class A present in namespaceForClass1");
- }
- }
- }
- }
Fully Qualified name
Let's take an example to understand this.
- namespace NameSpace1
- {
- namespace namespaceForClass1
- {
- public class A
- {
- public void classAMethod()
- {
- Console.WriteLine("I am method from Class A present in namespaceForClass1");
- }
- }
- }
- namespace namespaceForClass2
- {
- public class A
- {
- public void classAMethod2()
- {
- Console.WriteLine("I am method from Class A present in namespaceForClass2");
- }
- }
- }
- }
As shown in the above example, there are two namespaces "namespaceForClass1" and "namespaceForClass2"
present in NameSpace1 and and these two namespaces contain classes with the same name.
So, if we need to call any of the classes from these two interfaces and we use namespaces by using directive, then we will get the ambiguity error, as shown in the following screenshot.
Then, how to differentiate between the two?
Yes! The answer is - using a namespace fully qualified name.
As shown in the below example, when we use NameSpace1.namespaceForClass1.A, then we have classAMethod available to invoke but when we use NameSpace1.namespaceForClass2.A, then we get classAMethod2 to invoke.