/*
Learning C#
by Jesse Liberty
Publisher: O'Reilly
ISBN: 0596003765
*/
using System;
namespace InterfaceDemo
{
interface IStorable
{
void Read();
void Write(object obj);
int Status { get; set; }
}
// here's the new interface
interface ICompressible
{
void Compress();
void Decompress();
}
// Document implements both interfaces
class Document : IStorable
{
// the document constructor
public Document(string s)
{
Console.WriteLine("Creating document with: {0}", s);
}
// implement IStorable
publicvoid Read()
{
Console.WriteLine(
"Implementing the Read Method for IStorable");
}
publicvoid Write(object o)
{
Console.WriteLine(
"Implementing the Write Method for IStorable");
}
publicint Status
{
get { return status; }
set { status = value; }
}
// hold the data for IStorable's Status property
privateint status = 0;
}
publicclass TesterInterfaceDemoCasting
{
[STAThread]
staticvoid Main()
{
Document doc = new Document("Test Document");
// only cast if it is safe
if (doc is IStorable)
{
IStorable isDoc = (IStorable) doc;
isDoc.Read();
}
else
{
Console.WriteLine("Could not cast to IStorable");
}
// this test will fail
if (doc is ICompressible)
{
ICompressible icDoc = (ICompressible) doc;
icDoc.Compress();
}
else
{
Console.WriteLine("Could not cast to ICompressible");
} }
}
}