Saturday, October 25, 2008

Some points on using statement in C# !

* using Statement provides standard way of using objects which implements IDisposable interface.
*generally IDisposable objects are those wraps unmanaged resources in them & hence Dispose() method can be called to release unmanahed resource.
*If IDisposable object is declared & instantiated in using statement then Dispose() method will be automatically called while control leaving the using block.
*The IDisposable can be declared & instantiated as other objects noramally & call the Dispose() method to release unmanaged resources.
*But putting it in using statement ensures that the object is disposed even when any exception occured while calling methods on object.
*This is equivalent to intantiating IDisposable object in try/ catch block & calling Dispose() in finally block.
*With in the using block the object is readonly , it cant reassigned.

Below code shows how to use IDisposable objects

using (StreamReader streamreader = File.OpenText(@"FilePath"))


string filetext = streamreader.ReadToEnd();


No comments: