Csharp/CSharp Tutorial/Class/IDisposable with using

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Dispose() is called automatically when the using block exits

using System;
public class MyClass : IDisposable
{
  public MyClass(){}
  public void Dispose()
  {
    Console.WriteLine("In Dispose()");
  }
}
public class MainClass
{
  public static int Main(string[] args)
  {
    using(MyClass c = new MyClass())
    {
      
    }
    MyClass c1 = new MyClass();
    c1.Dispose();      
    return 0;
  } 
}
In Dispose()
In Dispose()

Use Not Disposible object in using statement

using System;
public class NotDisposible{}
public class MainClass
{
  public static void Main(string[] args)
  {
    // Uncomment to trigger compile time error.
    // using(NotDisposible x = new NotDisposible()){}
  } 
}