Namespaces and Class Libraries
Explore how to use namespaces to organize C# classes and avoid naming conflicts. Understand file-scoped and nested namespaces, and learn how to import and reference class libraries to reuse code effectively across multiple projects.
User-defined classes and structures do not exist in isolation. They are enclosed in containers called namespaces.
When we define a class, we usually place it inside a namespace to organize our code and prevent naming conflicts. The name of this namespace often matches the project name.
Line 1: Defines the namespace
MyFirstProject.Line 3: Defines the
Programclass inside the namespace.Line 5: The
Mainmethod serves as the entry point of the application.
Defining a namespace
A namespace is defined using the namespace keyword, followed by the name. In the example above, the full name of the Program class is MyFirstProject.Program.
The Program class can access other classes defined in the same namespace without a using directive:
Line 1: Declares the namespace
MyFirstProject.Line 7: Instantiates the
Employeeclass. BecauseEmployeeis in the same namespace, nousingdirective is required.Line 11: Defines the
Employeeclass within the same namespace block. ...