Adding using
Directives in Namespace Declarations
NOTE: The following content was included in the 4th Edition, but not later versions.
As of C# 10 and .NET 6, the most convenient way to add a namespace declaration within a file is to use file-scoped namespace declarations like this:
namespace SpaceGame.Physics;
public class Point
{
/* ... */
}
This is in contrast to the alternative (and formerly, only) approach, which includes curly braces and indentation:
namespace SpaceGame.Physics
{
public class Point
{
/* ... */
}
}
One advantage of the older style is that you can use multiple namespaces within a single file:
namespace SpaceGame.Physics
{
public class Point { /* ... */ }
}
namespace SpaceGame.UI
{
public class SpriteRenderer { /* ... */ }
}
People rarely do this, however.
But in the even that you find a need for this, one other thing to keep in mind is that you can also put in using
directives within the namespace declaration (not just at the top of the file) and use it within only that namespace:
namespace SpaceGame.Physics
{
using Microsoft.Win32;
public class Point { /* Has access to the simple name of things in the Microsoft.Win32 namespace here. */ }
}
namespace SpaceGame.UI
{
public class SpriteRenderer { /* No access to the simple names of things in Microsoft.Win32 here. Must use fully qualified name. */ }
}
In truth, it will be rare to actually want or need this type of fine-grained control, since things in different namespaces nearly always end up in different files, folders, or even projects.