Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

C# Dictionary

  1. Home
  2. C# Dictionary
  3. using (Namespace Import / Resource Disposal) (C#)

using (Namespace Import / Resource Disposal) (C#)

The using keyword in C# serves two distinct roles: importing namespaces and automatically releasing resources. C# uses the same keyword for two completely different purposes — a directive such as using System; that brings a namespace into scope, and a statement such as using (var r = ...) { } that ensures an object is disposed of when the block exits.

Syntax

using System;
using System.Collections.Generic;

// ② using statement. Dispose() is called automatically when the block exits.
using (var resource = new ResourceClass()) {
	// Code that uses the resource
} // ← resource.Dispose() is guaranteed to be called here.

// ③ using declaration (C# 8 and later). Disposed when the scope ends.
using var resource = new ResourceClass();
// Automatically disposed at the end of the enclosing scope (no braces needed).

// ④ global using (C# 10 and later). Applies to the entire project.
global using System;
global using System.Collections.Generic;

// ⑤ using static. Allows calling static members without the class name.
using static System.Console;
using static System.Math;
// You can write WriteLine("hello"); instead of Console.WriteLine("hello");

using Syntax Overview

SyntaxPurposeNotes
using Namespace;Namespace importWritten at the top of the file. Applies to that file only.
global using Namespace;Project-wide namespace importC# 10 and later. Typically collected in a dedicated file (GlobalUsings.cs).
using static ClassName;Direct access to static membersAllows omitting the class name, e.g. Math.Abs → Abs.
using (var x = ...) { }Automatic resource release (block form)Used with objects that implement IDisposable.
using var x = ...;Automatic resource release (declaration form)C# 8 and later. Disposed at the end of the enclosing scope.

Sample Code

UsingNamespace.cs
using System;
using System.Collections.Generic;

class UsingNamespace {
	static void Main() {

		// Because of "using System;", you can write Console.WriteLine instead of System.Console.WriteLine.
		Console.WriteLine("=== メンバー一覧 ===");

		// Because of "using System.Collections.Generic;", you can write List<T> without the namespace prefix.
		List<string> members = new List<string> {
			"member_01",
			"member_02",
			"member_03",
			"member_04",
			"member_05"
		};

		foreach (string name in members) {
			Console.WriteLine("  " + name);
		}
	}
}

This produces the following output:

dotnet script UsingNamespace.cs
=== メンバー一覧 ===
  member_01
  member_02
  member_03
  member_04
  member_05
UsingStatic.cs
using System;
// Allows direct access to static members without the class name prefix.
using static System.Console;
using static System.Math;

class UsingStatic {
	static void Main() {

		// "using static System.Console;" lets you omit the Console. prefix.
		WriteLine("=== 数値計算 ===");

		double baseEnergy = 1200.0;

		// "using static System.Math;" lets you omit the Math. prefix.
		double amplified = Round(baseEnergy * 1.75, 2);
		double maxEnergy = Max(amplified, 5000.0);

		WriteLine("基礎値: " + baseEnergy);
		WriteLine("強化後: " + amplified);
		WriteLine("上限適用後: " + maxEnergy);

		// PI can also be referenced without the Math. prefix.
		WriteLine("円の面積: " + Round(PI * 50 * 50, 2));
	}
}

This produces the following output:

dotnet script UsingStatic.cs
=== 数値計算 ===
基礎値: 1200
強化後: 2100
上限適用後: 5000
円の面積: 7853.98
UsingStatement.cs
using System;
using System.IO;

class UsingStatement {
	static void Main() {

		// StreamWriter implements IDisposable, so using ensures it is always closed.
		// Even if an exception is thrown, Dispose() is called when the block exits.
		string filePath = "output_log.txt";

		using (StreamWriter writer = new StreamWriter(filePath)) {
			// Write to the file inside the block.
			writer.WriteLine("=== 処理記録 ===");
			writer.WriteLine("task_01: completed");
			writer.WriteLine("task_02: in_progress");
			writer.WriteLine("task_03: completed");
		} // ← writer.Dispose() is called here, guaranteeing the file is closed.

		Console.WriteLine("処理記録を書き込みました。");

		// Dispose() is called automatically at the end of the scope (end of the method).
		using StreamReader reader = new StreamReader(filePath);
		string content = reader.ReadToEnd();
		Console.WriteLine("\n--- ファイルの内容 ---");
		Console.WriteLine(content);
		// ← reader.Dispose() is called at the end of the method.
	}
}

This produces the following output:

dotnet script UsingStatement.cs
処理記録を書き込みました。

--- ファイルの内容 ---
=== 処理記録 ===
task_01: completed
task_02: in_progress
task_03: completed
UsingIDisposable.cs
using System;

// A custom class that implements IDisposable.
// This example models a resource-managing class.
class ManagedResource : IDisposable {
	private string fieldName;
	private bool disposed = false; // Flag to prevent double disposal.

	public ManagedResource(string name) {
		fieldName = name;
		Console.WriteLine("[" + fieldName + "] リソース確保");
	}

	public void UseEnergy(string userName) {
		// Throw an exception if UseEnergy is called after disposal.
		if (disposed) {
			throw new ObjectDisposedException(fieldName, "すでにリソースが解放されています。");
		}
		Console.WriteLine("[" + fieldName + "] " + userName + " がリソースを使用しました。");
	}

	// Implementation of IDisposable.Dispose().
	public void Dispose() {
		if (!disposed) {
			Console.WriteLine("[" + fieldName + "] リソース解放。");
			disposed = true;
		}
	}
}

class UsingIDisposable {
	static void Main() {

		// ManagedResource.Dispose() is called automatically when the using block exits.
		using (ManagedResource field = new ManagedResource("resource_a")) {
			field.UseEnergy("process_1");
			field.UseEnergy("process_2");
		} // ← Dispose() is called here.

		Console.WriteLine();

		using ManagedResource field2 = new ManagedResource("resource_b");
		field2.UseEnergy("process_3");
		// Dispose() is called at the end of the method.
	}
}

This produces the following output:

dotnet script UsingIDisposable.cs
[resource_a] リソース確保
[resource_a] process_1 がリソースを使用しました。
[resource_a] process_2 がリソースを使用しました。
[resource_a] リソース解放。

[resource_b] リソース確保
[resource_b] process_3 がリソースを使用しました。
[resource_b] リソース解放。

Common Mistakes

Using the using statement on an object that does not implement IDisposable

The using statement / declaration can only be used with objects that implement the IDisposable interface. Writing using on a class that does not implement it causes a compile error.

// using (string s = "hello") { }

// using works with classes like StreamWriter and HttpClient that implement IDisposable.
using (StreamWriter w = new StreamWriter("log.txt")) {
	w.WriteLine("ok");
}

Misunderstanding the scope of a using declaration

With using var (the C# 8 declaration form), Dispose() is called at the end of the enclosing scope (typically the end of the method). If you need the resource to be released immediately, use the block form using (...) { } instead.

static void Example() {
	// Declaration form: not disposed until the end of the method.
	using var writer = new StreamWriter("data.txt");
	writer.WriteLine("data");
	// writer is still open here.

	// Block form: disposed immediately at the closing brace.
	using (var writer2 = new StreamWriter("data2.txt")) {
		writer2.WriteLine("data");
	} // Disposed here.
}

Overview

The using keyword in C# serves two roles: importing namespaces and automatically releasing resources. The namespace import directive omits the need for fully qualified names and is written at the top of the file. With global using introduced in C# 10, you can apply imports to all files in the project at once, eliminating repetitive declarations.

For resource management, wrapping an object that implements the IDisposable interface — such as a file, network connection, or database connection — in a using block guarantees that Dispose() is called when the block exits, even if an exception is thrown. This is equivalent to manually calling Dispose() in a try / finally block, but using is shorter and less error-prone. The using var declaration form introduced in C# 8 works without braces and releases the resource at the end of the variable's scope (the end of the method).

using static allows you to access static members directly without the class name prefix. For example, you can call Console.WriteLine as simply WriteLine. While this shortens code, be careful not to overuse it, as it can make it harder to tell which class a member belongs to. For more on resource release, see also try / catch / finally.

If you find any errors or copyright issues, please .