static void Main(string[] args)
{
using (UsingKeyword
obj = new UsingKeyword())
{
Console.WriteLine(obj.add());
}
Console.Read();
}
Now if we need to perform the clean up using while using our object and facilitate all the above mentioned functionalities we need to implement the IDisposable
pattern. Implementing IDisposable
pattern will force us to have a Dispose
function.
Secondly if the user want to use the try-finally
approach then also he can call this Dispose function and the object should release all the resources.
Lastly and most importantly, lets have a Finalizer
that will release the unmanaged resources when the object goes out of scope. The important thing here is to do this finalize only if the programmer is not using the 'using
' block and not calling the Dispose
explicitly in a finally block.
namespace BasicCsharp
{
public class UsingKeyword : IDisposable
{
public UsingKeyword()
{
}
public int add()
{
return 10 + 10;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private IntPtr
handle;
private Component
component = new Component();
private bool disposed
= false;
public UsingKeyword(IntPtr
handle)
{
this.handle = handle;
}
protected virtual void Dispose(bool
disposing)
{
if (!this.disposed)
{
if (disposing)
component.Dispose();
CloseHandle(handle);
handle = IntPtr.Zero;
disposed = true;
}
}
[System.Runtime.InteropServices.DllImport("Kernel32")]
private extern static Boolean
CloseHandle(IntPtr handle);
}
}