CHAPTER 8 WORKING WITH INTERFACES
// Nope! Multiple inheritance is not possible in C#
// for classes.
public class MiniVan : Car, CloneableType
{
}
As you would guess, interface types come to the rescue. After an interface has been defined, it can
be implemented by any class or structure, in any hierarchy, within any namespace or any assembly
(written in any .NET programming language). As you can see, interfaces are highly polymorphic.
Consider the standard .NET interface named ICloneable, defined in the System namespace. This
interface defines a single method named Clone():
public interface ICloneable
{
object Clone();
}
If you examine the .NET Framework 4.5 SDK documentation, you’ll find that a large number of
seemingly unrelated types (System.Array, System.Data.SqlClient.SqlConnection,
System.OperatingSystem, System.String, etc.) all implement this interface. Although these types have no
common parent (other than System.Object), we can treat them polymorphically via the ICloneable
interface type.
For example, if you had a method named CloneMe() that took an ICloneable interface parameter,
you could pass this method any object that implements said interface. Consider the following simple
Program class defined within a Console Application named ICloneableExample:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("***** A First Look at Interfaces *****\n");
// All of these classes support the ICloneable interface.
string myStr = "Hello";
OperatingSystem unixOS = new OperatingSystem(PlatformID.Unix, new Version(