Wednesday, June 3, 2015

Using statement in C#


using:

Using block/statement is used to free unmanaged resources.

Using statement is translated to three parts,
  • Acquisition
  • Usage
  • Disposal
This resource is first acquired, then the usage is enclosed in a try statement with a finally clause. The object then gets disposed in the finally clause.

using (MemoryStream objStream = new MemoryStream())
{
    objStream.WriteTo(Response.OutputStream);
}

this code gets translated to

MemoryStream objStream = new MemoryStream();
try
{
    objStream.WriteTo(Response.OutputStream);
}
finally
{
    if(objStream !=null)
       ((IDisposable)objStream).Dispose();
}


Objects that implement IDisposable can be used in a using statement. Calling Dispose() explicitly (or implicitly via a using statement) can have performance benefits.

"Code that is using a resource can call Dispose() to indicate that the resource is no longer needed. If Dispose() is not called, then automatic disposal eventually occurs as a consequence of garbage collection." - MSDN

In the below code we can observe the following points,
  • If we use using block along a Customer type, it give a compiler error, saying that "type used in a using statement must be implicitly convertible to 'System.IDisposable'".
  • Same if use with Student type, it does not give any error, because it implements System.IDisposable interface.
Sample code -

foreach loop in C#


foreach:

It repeats a group of embedded statements for each element in an array or an object collection. By a collection, we mean any class, struct, or interface that implements the IEnumerable interface.

foreach gives read-only access to the array contents, so we can not change the values of any of the elements.

Only forward iteration is possible in for-each loop.

The condition to work with IEnumerable objects is that the underlying collection must not change while you are accessing it. You can presume that the Enumerable object is a snap shot of the original collection, so if you tries to change the collection while enumerating, it will throw an exception. However the fetched objects in Enumeration is not immutable at all.

Since the variable used in foreach loop is local to the loop block this variable is however not available outside the block.

In the below code we can observe the following points,
  • If we try to modify the foreach iteration variable either primitive type (int) or a user defined class (Customer), we get compile time error.
  • If we try to add/remove any item from the collection, we get run time exception.
  • We can always modify the object properties (Name property in Customer type), which are not immutable.
Sample Code-