C Sharp dotnet the using statement
The using statement is used to set one or more resources. These resources are executed and then released. Using statement calls Dispose() after the using-block is left, even if the code throws an exception. So you basically call using for classes that require cleaning up after them. The statement is also used with database operations.
The main goal is to manage resources and release all the resources automatically.
Let us see an example where “A” would print first since the SystemResource is allocated first.
using System; using System.Text; class Demo { static void Main() { using (SystemResource res = new SystemResource()) { Console.WriteLine("A"); } Console.WriteLine("B"); } } class SystemResource : IDisposable { public void Dispose() { Console.WriteLine("C"); } }
Output:
A
C
B