Let’s go through namespace in C# β€” a fundamental feature for organizing code.


πŸ“Œ 1. What Is a Namespace?

  • A namespace is a logical container for classes, structs, enums, delegates, interfaces, and other types.

  • It prevents name collisions by grouping related types together.

  • Think of it as a folder structure for your code, but at the type level.


πŸ“Œ 2. Declaring a Namespace

Basic Syntax

namespace MyApplication
{
    class Program
    {
        static void Main()
        {
            Console.WriteLine("Hello from MyApplication namespace!");
        }
    }
 
    class Helper
    {
        public void DoWork()
        {
            Console.WriteLine("Working...");
        }
    }
}
  • Here, both Program and Helper belong to the MyApplication namespace.

πŸ“Œ 3. Nested Namespaces

  • Namespaces can be nested to further organize types.
namespace MyApplication.Utilities
{
    class Logger
    {
        public void Log(string message) => Console.WriteLine(message);
    }
}
 
namespace MyApplication.Models
{
    class User
    {
        public string Name { get; set; }
    }
}
  • MyApplication.Utilities.Logger and MyApplication.Models.User are fully qualified names.

πŸ“Œ 4. Using Namespaces

  • To use a type from another namespace, you use the using directive:
using MyApplication.Utilities;
 
class Program
{
    static void Main()
    {
        Logger log = new Logger();
        log.Log("Hello!");
    }
}
  • Without using, you must use the fully qualified name:
class Program
{
    static void Main()
    {
        MyApplication.Utilities.Logger log = new MyApplication.Utilities.Logger();
        log.Log("Hello!");
    }
}

πŸ“Œ 5. Key Points

FeatureNotes
namespaceGroups related types logically
Fully qualified namesInclude all parent namespaces (e.g., MyApplication.Utilities.Logger)
Prevents naming conflictsTwo classes with the same name in different namespaces are allowed
Can be nestedHelps organize large projects
Used with usingSimplifies code by avoiding full names

πŸ“Œ 6. Analogy

  • Namespace = a folder on your computer.

  • Class inside namespace = a file inside the folder.

  • Multiple folders can have files with the same name without conflict β€” same with namespaces and classes.


βœ… Summary:

  • Use namespace to organize code and avoid name collisions.

  • Combine with using for convenience.

  • Nested namespaces help structure large projects.