Hi Guys
NP113 using keyword
In the following program there is a using keyword (highlighted is yellow) which is new to me. Please explain the function of using keyword.
Thank you
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.InteropServices;
class MyClass : IDisposable
{
public event EventHandler OnInitialized;
public event EventHandler OnDisposed;
public void Init()
{
// Initialize our state...
EventHandler onInit = OnInitialized;
if (onInit != null)
onInit(this, new EventArgs());
}
public void Dispose()
{
// Release our state...
EventHandler onDisp = OnDisposed;
if (onDisp != null)
onDisp(this, new EventArgs());
}
}
public class MainClass
{
public static void Main()
{
using (MyClass f = new MyClass())
{
f.OnInitialized += delegate { Console.WriteLine("init"); };
f.OnDisposed += delegate { Console.WriteLine("disposed"); };
f.Init();
}
}
}
/*
init
disposed
*/
Posted Aug 5, 2008, 6:54 PM
Thank you for your explanation.
AlanPosted Aug 5, 2008, 6:38 PM
The 'using' statement (not to be confused with the 'using' directive) is a way of automatically implementing the 'disposable' pattern in C#. The idea is that you declare a variable in the using statement and assign it an object of a type which implements IDisposable.
This variable remains in scope throughout the block of code controlled by the using statement but is then destroyed and the Dispose() method is automatically called on the object to clean up any resources which it has been using.
In your example code, the using statement can be applied to a variable of MyClass type because it implements IDisposable and therefore has a Dispose() method.
It's good practice to use the 'using' statements with objects such as StreamReader, StreamWriter etc to guard against the possibility that you may forget to call the Close() method (which calls Dispose()) when you've finished with the object and the file handle will not therefore be released back to the operating system.
For more detail on this see this MSDN article:
http://msdn.microsoft.com/en-us/library/yh598w02.aspx