In C# the using
-keyword has 2 purposes: it includes a namespace, or manages the underlying resources of a type. Most C# files use the using
-keyword.
The using
-statement is combined with a type that implements the IDisposable
interface
. Things like StreamReader
or StreamWriter
implement IDisposable
.
This program defines a class
called SystemResource
. The class
implements the IDisposable
interface
and the required Dispose
method.
Main
method, we wrap the SystemResource
instance inside a using
-statement.SystemResource
instance is allocated upon the managed heap. Next the "1" is written.Dispose
method is invoked. And finally, the "2" is printed.Dispose
method is called immediately when control flow exits the using block.using System; using System.Text; class Program { static void Main() { // Use using statement with class that implements Dispose. using (SystemResource resource = new SystemResource()) { Console.WriteLine(1); } Console.WriteLine(2); } } class SystemResource : IDisposable { public void Dispose() { // The implementation of this method not described here. // ... For now, just report the call. Console.WriteLine(0); } }1 0 2
It is possible to nest multiple using
-statements one after another. You do not need to use any curly brackets in this case.
using
-statements, you can use the variables declared in previous using statements as well.using System; class Program { static void Main() { using (SystemResource resource1 = new SystemResource()) using (SystemResource resource2 = new SystemResource()) { Console.WriteLine(1); } } } class SystemResource : IDisposable { public void Dispose() { Console.WriteLine(0); } }
The using
-keyword in C# is also used to include a namespace during compilation. This is what "using System
" lines do at the top of files.
using System; class Program { static void Main() { // Console is in the System namespace. Console.WriteLine("Hello"); } }Hello
We can place the keyword "global" before a using directive to indicate that the entire project should include the using directive. This can reduce source file size.
Program.cs
file has a global using for the System
namespace, so Test.cs
can access Console
without a using System
directive.// Program.cs global using System; class Program { static void Main() { Test.Print(); } } // Test.cs static class Test { public static void Print() { Console.WriteLine("Hello"); } }Hello
It is most common to use "using" with types already defined in .NET. Some of these types include BinaryReader
, BinaryWriter
, DataTable
.
using
-statement. You do not need to implement any interfaces.For the using namespace feature, we can specify an alias for a namespace. This can reduce redundant text in source files.
A using
-block invokes the Dispose
method found in the IDisposable
interface
implementation. Meanwhile a using
-statement includes a namespace during compilation.