Thursday, June 21, 2012

IDisposable and using in C#

http://msdn.microsoft.com/en-us/library/yh598w02%28v=vs.80%29.aspx tells us that in order for a class to use a using loop that it must inheirt from IDisposable.

using System;
   
class C : IDisposable
{
   public void UseLimitedResource()
   {
      Console.WriteLine("Using limited resource...");
   }
   
   void IDisposable.Dispose()
   {
      Console.WriteLine("Disposing limited resource.");
   }
}
   
class Program
{
   static void Main()
   {
      using (C c = new C())
      {
         c.UseLimitedResource();
      }
      Console.WriteLine("Now outside using statement.");
      Console.ReadLine();
   }
}

No comments:

Post a Comment