Namespaces (namespaces) are an organizational tool in the .NET framework that allows us to group related classes and other code elements under a single name.
Namespaces allow us to avoid naming conflicts between different elements. For example, imagine two libraries that use the same name Cliente. With namespaces we avoid the conflict and ambiguity.
Namespaces are useful for maintaining order in projects as they grow in size. Thus, they allow us to organize an application’s logic and separate functionalities into different areas.
Creating a namespace
Creating a Namespace in .NET is done by declaring the namespace keyword followed by the name we want to give it.
Then, inside the braces, we place the related classes and other programming elements.
namespace MiEspacioDeNombres
{
public class MiClase
{
// Class code
}
}
In this example, MiEspacioDeNombres is the Namespace containing the definition of MiClase.
Using namespaces
To use a Namespace in a C# program, we can do it in two ways:
We can use the full name of a type, which means including the Namespace before the type name (this is called full qualified).
For example, if we have a Namespace called MiPrograma and a class called MiClase, we can use it as follows:
MiPrograma.MiClase miObjeto = new MiPrograma.MiClase();
Another way to use a Namespace is by importing it in the using section (at the beginning of the file). This allows us to use the type name directly without having to specify the full Namespace.
using MyProgram;
// ...
MyClass myObject = new MyClass();
In this case, it is not necessary to use the full name MyProgram.MyClass, since the Namespace has been imported with using.
Nested Namespaces
Namespaces can be nested. That is, a Namespace can contain other Namespaces. This allows for a hierarchical organization of code (although it is not particularly common).
namespace Company
{
namespace Project
{
public class MainClass
{
// Class code
}
}
}
To access MainClass, you can use Company.Project.MainClass or import the nested namespace:
using Company.Project;
public class SecondaryClass
{
public void Method()
{
MainClass instance = new MainClass();
}
}
Namespace Aliases
In some cases, it may be useful to define an alias for a Namespace. This is useful
- If the Namespace name is long
- If there are naming conflicts
To do this, we use the using keyword followed by an alias and the Namespace. Like this:
using Alias = Long.Namespace.Name;
public class ClassWithAlias
{
public void Method()
{
Alias.Class instance = new Alias.Class();
}
}
Static Namespaces
C# also allows importing static members of a class, known as using static. This is useful for accessing static methods and constants without having to specify the full class name.
using static System.Math;
public class Calculator
{
public double CalculateHypotenuse(double a, double b)
{
return Sqrt(a * a + b * b);
}
}
In this example,
Sqrtis a static method of theSystem.Mathclass- Thus, we can invoke it directly without prefixing it with
Math
