A safe method of determining whether a class implements a particular interface

image_pdfimage_print

   

/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa

Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
//
//  ISample.cs - Demonstrates a safe method of determining whether a class
//               implements a particular interface
//               Compile this program with the following command line:
//                   C:>csc isample.cs
//
namespace nsInterfaceSample
{
    using System;
    public class InterfaceSample
    {
        static public void Main ()
        {
// Declare an instance of the clsSample class
            clsSample samp = new clsSample();
//  Test whether clsSample supports the IDisposable interface
            if (samp is IDisposable)
            {
//  If true, it is safe to call the Dispose() method
                IDisposable obj = (IDisposable) samp;
                obj.Dispose ();
            }
        }
    }
    class clsSample : IDisposable
    {
//  Implement the IDispose() function
        public void Dispose ()
        {
            Console.WriteLine ("Called Dispose() in clsSample");
        }
    }
}