C# Examples


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

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

See also

  • C# Foreach - how foreach and IEnumerable works debuggable online
  • C# Switch - switch statement examples debuggable online
  • C# Using - using statement examples debuggable online


By Jan Slama, 02-Feb-2016