C# - namespace

In C#, a namespace is a way to organize your code into a container where you can define classes, interfaces, structs, enums, and delegates. This is helpful in large projects to avoid naming conflicts, where two classes might have the same name but perform different functions. By placing these classes in different namespaces, we can avoid the conflict and also make our code easier to read and maintain.

Here's an analogy: think of a namespace as a folder on your computer. If you have two files with the same name but they're in different folders, you can still distinguish between them easily because of the folder structure. Similarly, namespaces help keep classes and other types in separate logical compartments.

Let's illustrate this with an example. Suppose we have two groups in a library system, Administration and Catalog, and both groups have a class called Report. We can use namespaces to differentiate these classes.


// Define a namespace for the Administration group
namespace LibrarySystem.Administration
{
    // Define a Report class within the Administration namespace
    public class Report
    {
        public void GenerateAdminReport()
        {
            // Code to generate an administration report
            Console.WriteLine("Generating administration report...");
        }
    }
}

// Define a namespace for the Catalog group
namespace LibrarySystem.Catalog
{
    // Define a Report class within the Catalog namespace
    public class Report
    {
        public void GenerateCatalogReport()
        {
            // Code to generate a catalog report
            Console.WriteLine("Generating catalog report...");
        }
    }
}

// Example of using namespaces
class Program
{
    static void Main()
    {
        // Create a Report object from the Administration namespace
        LibrarySystem.Administration.Report adminReport = new LibrarySystem.Administration.Report();
        adminReport.GenerateAdminReport();

        // Create a Report object from the Catalog namespace
        LibrarySystem.Catalog.Report catalogReport = new LibrarySystem.Catalog.Report();
        catalogReport.GenerateCatalogReport();
    }
}

Explanation of the code:

  • We have defined two Report classes, but each is in a different namespace (LibrarySystem.Administration and LibrarySystem.Catalog), which keeps them separate even though they have the same name.
  • In the Main method, when we want to create an instance of a Report, we have to specify which namespace's Report we want to use by prefixing it with the namespace name. This fully qualifies the class name and removes any ambiguity for the compiler.
  • adminReport.GenerateAdminReport() and catalogReport.GenerateCatalogReport() call the methods from the respective Report classes.

Namespaces are also helpful for extension methods, keeping internal classes private to a library, and much more. They're a fundamental part of organizing C# programs.