C# Namespaces

HTML
CSS
Bootstrap
JavaScript
C#
SQL
Salesforce Admin
Exercise
Study Material

Namespaces in C#

 

Organizing Code:

A namespace is a way to organize related code elements, such as classes, interfaces, and enums, into a hierarchical structure.

It helps prevent naming conflicts and enhances code readability.

// Example namespace

namespace MyProject.Utilities

{

    public class Logger

    {

        // Logger implementation

    }

 

    public class FileHandler

    {

        // FileHandler implementation

    }

}

Using Directives:

The using directive is used to inform the compiler about the namespaces used in a file.

It allows you to reference types without fully qualifying their names.

// Using a namespace in a C# file

using MyProject.Utilities;

 

public class Program

{

    public static void Main()

    {

        Logger myLogger = new Logger();

        FileHandler myHandler = new FileHandler();

    }

}

Creating and Using Your Own Namespace:

You can define your own namespace to organize related code elements within a project.

// Defining a namespace

namespace MyProject.Mathematics

{

    public class Calculator

    {

        public int Add(int a, int b)

        {

            return a + b;

        }

    }

}

// Using the custom namespace

using MyProject.Mathematics;

 

public class Program

{

    public static void Main()

    {

        Calculator myCalc = new Calculator();

        int sum = myCalc.Add(5, 10);

    }

}

Nested Namespaces:

Namespaces can be nested, providing a way to further organize related code.

// Nesting namespaces

namespace MyProject.Utilities

{

    public class Logger

    {

        // Logger implementation

    }

 

    namespace FileHandling

    {

        public class FileHandler

        {

            // FileHandler implementation

        }

    }

}

// Using nested namespaces

using MyProject.Utilities.FileHandling;

 

public class Program

{

    public static void Main()

    {

        Logger myLogger = new Logger();

        FileHandler myHandler = new FileHandler();

    }

}

Best Practices:

Choose meaningful and consistent names for your namespaces, reflecting the purpose and content of the contained code.

// Good: Meaningful and consistent namespace

namespace MyProject.Utilities

{

    // …

}

 

// Avoid: Vague or inconsistent namespace

namespace Util

{

    // …

}

Keep namespaces reasonably shallow to avoid overly complex hierarchies.

// Good: Clear and concise namespace structure

namespace MyProject.Utilities

{

    // …

}

 

// Avoid: Excessively deep namespace structure

namespace MyProject.Utilities.Logging.FileHandling

{

    // …

}