|
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 : FooBase, IA {
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
|