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

The using directive can create aliases to namespaces:

using MyNamespace = Really.Long.Nested.Namespace;

ℹ️ Important

Availability: C# 12

Or, to a type:

using WpfButton = System.Windows.Controls.Button;
using WinFormsButton = System.Windows.Forms.Button;

var wpfButton = new WpfButton();
var winFormsButton = new WinFormsButton();

Including generic types:

using StringList = System.Collections.Generic.List<string>;

var strings = new StringList { "C#", "TypeScript" };

Even a Tuple:

using MyTuple = (int Min, int Max);

But not a reference type:

// ILLEGAL
using X = string?;

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)) {  }