13 May 2013

prerequisite for C# .NET "using" keyword

Prerequisite for "using" keyword:

To use "using" keyword, the class has to implement IDisposable interface. If not there will be compile time error.

class Program
{
  public static void Main(string[] args)
  {
  using (ClientManager clientManager = new ClientManager())
    {
     // Your logic
    }
  }
}
When you compile the above code, you will get the below compile time error:

"type used in a using statement must be implicitly convertible to 'System.IDisposable'."

This is because ClientManager has not implemented the IDisposable interface.

Resolving the compile time error:

When the class ClientManager implements the System.IDisposable compile time error will disappear. Then ClientManager class can be used inside the using statement.

public class ClientManager:  IDisposable 
{
 public void Dispose()
  {
    // Your class dispose logic
  }
}

More on C# .NET using keyword

You can refer one more interview question on C# .NET "using" keyword.