ViIvanov

Explicit IDisposable

Dec 12th, 2013
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.55 KB | None | 0 0
  1. using System;
  2.  
  3. class D : IDisposable
  4. {
  5.   void IDisposable.Dispose() { }
  6. }
  7.  
  8. static class Program
  9. {
  10.   static void Main() {
  11.     var d = new D();
  12.  
  13.     // #1 Looks like typecast
  14.     ((IDisposable)d).Dispose();
  15.  
  16.     // #2 Temporary variable w/o typecast
  17.     IDisposable dd = d;
  18.     dd.Dispose();
  19.  
  20.     // #3 - Calling extension
  21.     d.Dispose();
  22.   }
  23.  
  24.   static void Dispose<T>(this T instance) where T : IDisposable {
  25.     if(instance == null) {
  26.       throw new ArgumentNullException("instance");
  27.     }//if
  28.  
  29.     instance.Dispose();
  30.   }
  31. }
Advertisement
Add Comment
Please, Sign In to add comment