find and solve || findandsolve.com
Please wait.....

C# Namespaces

In the C#, namespaces are used to organize and provide multiple classes, structs, interfaces, enums and delegates. It use to control the scope of methods and classes in larger .Net programming.

In a simple C# program we use Console.WriteLine in console application where System is the namespace and Console is the class. To access the class of a namespace, you need to use namespace class name. You can use using keyword so that you don't have to use complete name all the time.

A namespace can have following types as its members:

  • Namespaces (Nested Namespace)
  • Classes
  • Interfaces
  • Structures
  • Delegates

C# namespace using keyword example

using System; //this is using keyword 
namespace NameSpaceExample//this is created namespace
{
    public class Program
    {
       public static void Main(string[] args)
        {
          Console.WriteLine("Hello FindAndSolve");
        }
    }
}  

Output

Hello FindAndSolve

C# Define a Multiple Namespaces

In c#, you can define and access multiple namespaces in your application with using keyword.

Example

using System;  
namespace FirstNameSpace {
public class FirstHelloClass {
    public void sayHello() { Console.WriteLine("Hello First Namespace"); }
}
}
namespace SecondNameSpace
{
    public class SecondHelloClass
    {        public void sayHello() { Console.WriteLine("Hello Second Namespace"); }
    }
}
public class TestNamespace {     public static void Main()
    {
        FirstNameSpace.FirstHelloClass objFirst = new FirstNameSpace.FirstHelloClass();
        SecondNameSpace.SecondHelloClass objSecond = new SecondNameSpace.SecondHelloClass();         objFirst.sayHello();
        objSecond.sayHello();
    }
}  

Output

Hello First Namespace

Hello Second Namespace

Nested Namespaces in C#

In the c#, a namespace under another namespace  is called a Nested Namespace. The nested namespace classes and their class or member can be accessed by using the dot (.) operator like as given below.

Syntax

namespace MainNameSpace{
    namespace NestedNameSpace{
    // Nested Namespace Code
    }
}

Example

using System;
using CustomNameSpace.Nested;
namespace FindAndSolve
{
    public class Program
    {
        public static void Main(string[] args)
        {
             Welcome w = new Welcome();
             w.GreetMessage();
        }
    }
}
namespace CustomNameSpace {
      namespace Nested       {           public class Welcome
          {
              public void GreetMessage()
              {
                  Console.WriteLine("Welcome to FinsAndSolve");
              }
          }
      }
}

Output

Welcome to FinsAndSolve