Namespaces and Class Libraries
Learn about namespaces and their role when creating class libraries.
We'll cover the following
Namespaces
All user-defined classes and structures, as a rule, don’t exist in a vacuum, but are enclosed in special containers called namespaces. The Program
class generated by default upon the creation of a new .NET project already resides in a namespace. The name of this namespace is usually the same as the name of the project:
namespace MyFirstProject
{
class Program
{
static void Main(string[] args)
{
}
}
}
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 sees all other classes defined in the same namespace
:
namespace MyFirstProject
{
class Program
{
static void Main()
{
Employee employee = new Employee();
}
}
class Employee
{
}
}
Importing namespaces
To use classes from other namespaces, the others must be imported with the using
directive:
using System;
The above statement lets us use all classes from the System
namespace
, including the Console
class that’s used to print to the console:
Console.WriteLine("Hello World!");
If we opt not to bring the System
namespace
, we have to use the full name of the class to access its members:
System.Console.WriteLine("Hello World!");
Consider the following code. Inspect it and make it run.
Get hands-on with 1400+ tech skills courses.