The using keyword is well known to C# developers. Its main purpose, the using directive, is to create a shortcut to namespaces used in the code, but it’s not the only purpose. using can also be used to access an object in a bounded scope if this object’s type implements the IDisposable interface, which means it contains a public Dispose() method. #2
From MSDN:
IDisposable.Dispose Method
Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.#1
[csharp title=”<h4>Example implementation of IDisposable for 'using' scope</h4>”]
public class LoggerScope : IDisposable
{
private ILog logger;
public LoggerScope(ILog logger)
{
this.logger = logger;
logger.Error("================== {0} scope started ======================", logger.Logger.Name);
}
#region Implementation of IDisposable
public void Dispose()
{
logger.Error("================== {0} scope ended ======================", logger.Logger.Name);
}
#endregion
}
[/csharp]
[csharp title=”<h4>Usage example</h4>”]
using (new LoggerScope(Loggers.BindLogger))
{
// your code here e.g. Logger.Write("error/info data");
}
[/csharp]
Resources
- IDisposable Interface (System).
- The using Keyword and IDisposable