C# Using Statement Examples

Following examples show using statement and IDisposable interface. You can debug examples online.

Using Statement vs Try-Finally

The following example shows using statement and how it is implemented under the hood with try-finally statement. In fact, the close curly bracket of the using statement is finally part in which the IDisposable.Dispose method is called.

C# Using
C# Try-Finally Equivalent
Output

IDisposable Interface

IDisposable is interface with a single method Dispose. It allows consumer of the class to immediately release allocated unmanaged resources (such as file handles, streams, device contexts, network connections, database connections). If the class doesn't implement IDisposable, consumer of the class have to wait non-deterministic amount of time to garbage collector when it performs object finalization.

Using Statement and IDisposable Implementation

This example shows using statement with custom implementation of IDisposable. The Dispose method is called at the end of the using scope.

C# Using
C# IDisposable Implementation
Output

See also

Tips

By Jan Slama, 02-Feb-2016
;