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 |
---|
using (var streamReader = new StreamReader("c:\\file.txt"))
{
Console.Write(streamReader.ReadToEnd());
}
|
C# Try-Finally Equivalent |
---|
{
var streamReader = new StreamReader("c:\\file.txt");
try
{
Console.Write(streamReader.ReadToEnd());
}
finally
{
if (streamReader != null)
streamReader.Dispose();
}
}
|
Output |
---|
Hello
|
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 |
---|
using (var myDisposable = new MyDisposable())
{
myDisposable.DoSomething();
}
|
C# IDisposable Implementation |
---|
public class MyDisposable : IDisposable
{
public MyDisposable() { Console.WriteLine("Allocating resources"); }
public void DoSomething() { Console.WriteLine("Using resources"); }
public void Dispose() { Console.WriteLine("Releasing resources"); }
}
|
Output |
---|
Allocating resources
Using resources
Releasing resources
|
See also
- MSDN using - using keyword in C# Reference
- MSDN IDisposable - IDisposable interface in MSDN
- C# Foreach - how foreach and IEnumerable works debuggable online
- C# Switch - switch statement examples debuggable online
- C# Using - using statement examples debuggable online
Tips
- [C#] String Format for DateTime – format date and time popular
- [C#] String Format for Double – format float numbers popular