Light Mode Image

C# Namespace

Namespace is a way to organize and group related code elements such as classes, interfaces, structures, enums, and delegates.

 

It helps in avoiding naming conflicts and provides a way to organize code in a hierarchical manner.

 

Namespaces are used to create a logical separation of code and to avoid naming collisions between different parts of a program.

 

Here's a simple example of a namespace in C#:

namespace MyNamespace
{
    class MyClass
    {
        public void MyMethod()
        {
            Console.WriteLine("Hello from MyMethod!");
        }
    }
}

 

In this example, the MyNamespace is the namespace, and MyClass is a class within that namespace. To use this class in another part of your code, you typically include a using directive at the top of your file:

using System;

class Program
{
    static void Main()
    {
        MyNamespace.MyClass myObject = new MyNamespace.MyClass();
        myObject.MyMethod();
    }
}

 

Alternatively, you can use an alias for the namespace to simplify the code:

using MyAlias = MyNamespace;

class Program
{
    static void Main()
    {
        MyAlias.MyClass myObject = new MyAlias.MyClass();
        myObject.MyMethod();
    }
}

 

This way, you can avoid typing the full namespace every time you use a class from that namespace.

 

Namespaces are particularly useful in larger projects where you may have many classes and want to organize them to prevent naming conflicts.