Home
Browse all 647 examples
Download all 647 examples
Download sample chapters
Reviews
Errata
Acknowledgments
Links on .NET
Paradoxal Press

Buy directly from Paradoxal Press at $33.99 (Save 43%)



Category: Programming
Level: Beginner to seasoned
900 pages
ISBN-10 097661322-0
ISBN-13 978-097661322-0
$59.99 USA
$79.99 CANADA


Listing 12-15 extracted from chapter Inheritance, polymorphism and abstraction


Listing 12-14<     > Listing 12-16


This listing can be compiled with the command line:
csc.exe /target:exe Example_12_15.cs
Errors: 0 Warnings: 0


Example_12_15.cs
using System;
interface IA { void f( int i ); }
interface IB { void g( int i ); }
abstract class FooBase { public abstract void h(int i); }
class FooDerived : FooBaseIA {
   public void f( int i ) { /*...*/ }
   public override void h( int i ){ /*...*/ }
}
class Program {
   static void Main() {
      IA refA = new FooDerived();
      IB refB = null;
      FooBase refAbst = null;
      FooDerived refC = null;
      // This test returns true at runtime.
      if ( refA is FooBase ) {
         refAbst = (FooBase) refA;
         // use refAbst...
      }
      // This test returns true at runtime.
      if ( refA is FooDerived ) {
         refC = (FooDerived) refA;
         // use refC...
      }
      // This test returns false at runtime.
      if ( refA is IB ) {
         refB = (IB) refA;
         // use refB...
      }
      // The C# compiler detects that 'refA' is typed with 'IA'. 
      // As a consequence it emits:  'if( refA!= null )'.
      if ( refA is IA ) { /*...*/ }
   }
}	
Copyright Patrick Smacchia 2006 2007