Namespaces in C#


A group named Namespace is designed to provide a way to keep it separate from the other. The name of the class declared in a namespace does not conflict with the same class names declared in the second category..


namespace namespace_name {
   // code declarations
}


To call the namespace-enabled version of a function or variable, keep the namespace name as follows −
namespace_name.item_name;
using System;

namespace first_space {

   class namespace_cl {
   
      public void func() {
         Console.WriteLine("Inside first_space");
      }
   }
}

namespace second_space {

   class namespace_cl {
   
      public void func() {
         Console.WriteLine("Inside second_space");
      }
   }
}

class TestClass {

   static void Main(string[] args) {
      first_space.namespace_cl fc = new first_space.namespace_cl();
      second_space.namespace_cl sc = new second_space.namespace_cl();
      fc.func();
      sc.func();
      Console.ReadKey();
   }
}

using Keyword

The keyword used to describe is that the program is using names in the given name space. For example, we are using system namespaces in our programs. The class console is defined there. We just write -

Console.WriteLine ("Hello there");
We could have written the fully qualified name as −
System.Console.WriteLine("Hello there");

using System;
using first_space;
using second_space;

namespace first_space {

   class abc {
   
      public void func() {
         Console.WriteLine("Inside first_space");
      }
   }
}

namespace second_space {

   class efg {
   
      public void func() {
         Console.WriteLine("Inside second_space");
      }
   }
}   

class TestClass {

   static void Main(string[] args) {
      abc fc = new abc();
      efg sc = new efg();
      fc.func();
      sc.func();
      Console.ReadKey();
   }
}

Nested Namespaces

namespace namespace_name1 {
   
   // code declarations
   namespace namespace_name2 {
      // code declarations
   }
}
using System;
using first_space;
using first_space.second_space;

namespace first_space {

   class abc {
   
      public void func() {
         Console.WriteLine("Inside first_space");
      }
   }
   
   namespace second_space {
   
      class efg {
      
         public void func() {
            Console.WriteLine("Inside second_space");
         }
      }
   }   
}
 
class TestClass {

   static void Main(string[] args) {
      abc fc = new abc();
      efg sc = new efg();
      fc.func();
      sc.func();
      Console.ReadKey();
   }
}


Share on Google Plus

About It E Research

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment