HI WELCOME TO SIRIS

C# Namespaces

Leave a Comment
Namespaces in C# are used to organize too many classes so that it can be easy to handle the application.
In a simple C# program, we use System.Console where System is the namespace and Console is the class. To access the class of a namespace, we need to use namespacename.classname. We can use using keyword so that we don't have to use complete name all the time.
In C#, global namespace is the root namespace. The global::System will always refer to the namespace "System" of .Net Framework.

C# namespace example

Let's see a simple example of namespace which contains one class "Program".
  1. using System;  
  2. namespace ConsoleApplication1  
  3. {  
  4.     class Program  
  5.     {  
  6.         static void Main(string[] args)  
  7.         {  
  8.             Console.WriteLine("Hello Namespace!");  
  9.         }  
  10.     }  
  11. }  
Output:
Hello Namespace!

C# namespace example: by fully qualified name

Let's see another example of namespace in C# where one namespace program accesses another namespace program.
  1. using System;  
  2. namespace First {  
  3. public class Hello  
  4. {  
  5.     public void sayHello() { Console.WriteLine("Hello First Namespace"); }  
  6. }  
  7. }  
  8. namespace Second  
  9. {  
  10.     public class Hello  
  11.     {  
  12.         public void sayHello() { Console.WriteLine("Hello Second Namespace"); }  
  13.     }  
  14. }  
  15. public class TestNamespace  
  16. {  
  17.     public static void Main()  
  18.     {  
  19.         First.Hello h1 = new First.Hello();  
  20.         Second.Hello h2 = new Second.Hello();  
  21.         h1.sayHello();  
  22.         h2.sayHello();  
  23.   
  24.     }  
  25. }  
Output:
Hello First Namespace
Hello Second Namespace

C# namespace example: by using keyword

Let's see another example of namespace where we are using "using" keyword so that we don't have to use complete name for accessing a namespace program.
  1. using System;  
  2. using First;  
  3. using Second;  
  4. namespace First {  
  5. public class Hello  
  6. {  
  7.     public void sayHello() { Console.WriteLine("Hello Namespace"); }  
  8. }  
  9. }  
  10. namespace Second  
  11. {  
  12.     public class Welcome  
  13.     {  
  14.         public void sayWelcome() { Console.WriteLine("Welcome Namespace"); }  
  15.     }  
  16. }  
  17. public class TestNamespace  
  18. {  
  19.     public static void Main()  
  20.     {  
  21.         Hello h1 = new Hello();  
  22.         Welcome w1 = new Welcome();  
  23.         h1.sayHello();  
  24.         w1.sayWelcome();  
  25.     }  
  26. }  
Output:

Hello Namespace
Welcome Namespace

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.