C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Note: In the Main method, we wrap the SystemResource instance inside a using statement.
On execution: First the SystemResource instance is allocated upon the managed heap. Next the "1" is written.
And: The "0" is written because the Dispose method is invoked. And finally, the "2" is printed.
Info: As demonstrated, the Dispose method is called immediately when control flow exits the using block.
C# program that uses using statement
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);
}
}
Output
1
0
2
Tip: In the second or further using statements, you can use the variables declared in previous using statements as well.
C# program that nests using blocks
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);
}
}
Info: Use a resource acquisition expression inside the using statement. You do not need to implement any interfaces.