illustrates casting an object to an interface
/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
Example8_4.cs illustrates casting an object
to an interface
*/
using System;
// define the IDrivable interface
interface IDrivable
{
// method declarations
void Start();
void Stop();
// property declaration
bool Started
{
get;
}
}
// Car class implements the IDrivable interface
class Car : IDrivable
{
// declare the underlying field used by the Started property
private bool started = false;
// implement the Start() method
public void Start()
{
Console.WriteLine("car started");
started = true;
}
// implement the Stop() method
public void Stop()
{
Console.WriteLine("car stopped");
started = false;
}
// implement the Started property
public bool Started
{
get
{
return started;
}
}
}
public class Example8_4
{
public static void Main()
{
// create a Car object
Car myCar = new Car();
// use the is operator to check that myCar supports the
// IDrivable interface
if (myCar is IDrivable)
{
Console.WriteLine("myCar supports IDrivable");
}
// cast the Car object to IDrivable
IDrivable myDrivable = (IDrivable) myCar;
// call myDrivable.Start()
Console.WriteLine("Calling myDrivable.Start()");
myDrivable.Start();
Console.WriteLine("myDrivable.Started = " +
myDrivable.Started);
// call myDrivable.Stop()
Console.WriteLine("Calling myDrivable.Stop()");
myDrivable.Stop();
Console.WriteLine("myDrivable.Started = " +
myDrivable.Started);
// cast the Car object to IDrivable using the as operator
IDrivable myDrivable2 = myCar as IDrivable;
if (myDrivable2 != null)
{
Console.WriteLine("Calling myDrivable2.Start()");
myDrivable2.Start();
Console.WriteLine("Calling myDrivable2.Stop()");
myDrivable2.Stop();
Console.WriteLine("myDrivable2.Started = " +
myDrivable2.Started);
}
}
}
Related examples in the same category