Namespaces
Namespaces declare scopes:
namespace SomeNamespace
{
class SomeClass { }
}
Namespace declarations can also be file-scoped:
using SomeNamespace; // Imports all classes from namespace.
Imports (using
Directive)
using SomeNamespace;
Aliases
using SomeAlias = Really.Long.Nested.Namespace;
Global
The global
modifier has the same effect as adding the same using
directive to every source file in a project:
global using SomeNamespace;
Can also be added to project file instead:
<Using>namespace</Using>
Static
The static modifier imports only the static members and nested types from a namespace:
static using SomeNamespace;
using static System.Console; // Imports a type's methods, like WriteLine.
Implicit Using Directives
Some SDKs have implicit using directives. For example, for console applications (Microsoft.Net.Sdk
):
System
System.IO
System.Collections.Generic
System.Linq
System.Net.Http
System.Threading
System.Threading.Tasks
Disabling
To disable implicit imports, add this line to the project file:
<ImplicitUsings>disable</ImplicitUsings>
To use implicit imports but remove a specific one:
<ItemGroup>
<Using Remove="System.Net.Http" />
</ItemGroup>
Using Statement
The using
statement generates a finally
statement that calls the Dispose()
method on an object that implements IDisposable
:
using (FileStream xmlFileStream = File.Create(file.xml)) { … }