Using Directives
Using Directives
Section titled βUsing DirectivesβWhat it means
Section titled βWhat it meansβA using directive imports a namespace so you can reference its types by their short name instead of the fully-qualified path. C# also has using statements (a different, unrelated meaning) for automatically disposing objects that hold unmanaged resources, and global using (C# 10+) to apply a using directive project-wide instead of per-file.
Examples
Section titled βExamplesβusing System;using System.Collections.Generic;using System.Linq;
var numbers = new List<int> { 1, 2, 3 }; // List<T> available without System.Collections.Generic.List<T>var evens = numbers.Where(n => n % 2 == 0); // Where() available via System.Linq
// using ALIAS -- give a namespace or type a shorter/different nameusing Json = System.Text.Json.JsonSerializer;var text = Json.Serialize(numbers);
// using STATEMENT -- automatically disposes the object at the end of the blockusing (var file = new StreamReader("data.txt")){ string content = file.ReadToEnd();} // file.Dispose() called automatically here, even if an exception occurs
// global using (in a shared file, C# 10+) -- applies to every file in the project// global using System;Common mistake
Section titled βCommon mistakeβConfusing the using directive (imports a namespace) with the using statement (disposes a resource) β they share a keyword but do completely unrelated things, which trips up developers new to C#.
// This is a DIRECTIVE -- import System.IO's typesusing System.IO;
// This is a STATEMENT -- dispose `file` when the block endsusing (var file = new StreamReader("data.txt")){ // ...}
// Easy to misread which one you're looking at without contextQuick practice
Section titled βQuick practiceβ-
Whatβs the difference between a
usingdirective and ausingstatement?Answer
Ausingdirective (at the top of a file, likeusing System;) imports a namespace; ausingstatement (using (var x = ...) { }) automatically callsDispose()on an object when the block ends. -
What does
global using(C# 10+) let you do?Answer
Apply ausingdirective across the entire project from one shared file, instead of repeating the same imports at the top of every individual file. -
What guarantee does a
usingstatement give you that manually callingDispose()doesnβt?Answer
It callsDispose()automatically even if an exception is thrown inside the block, whereas a manualDispose()call at the end of a method would be skipped if an earlier line throws.