CHAPTER 8 WORKING WITH INTERFACES
}
// Properties
string ConnectionString { get; set;}
int ConnectionTimeout { get; }
string Database { get; }
ConnectionState State { get; }
Note By convention, .NET interfaces are prefixed with a capital letter “I.” When you are creating your own
custom interfaces, it is considered a best practice to do the same.
Don’t concern yourself with the details of what these members actually do at this point. Simply
understand that the IDbConnection interface defines a set of members that are common to all ADO.NET
connection objects. Given this, you are guaranteed that every connection object supports members such
as Open(), Close(), CreateCommand(), and so forth. Furthermore, given that interface members are always
abstract, each connection object is free to implement these methods in its own unique manner.
As you work through the remainder of this book, you’ll be exposed to dozens of interfaces that ship
with the .NET base class libraries. As you will see, these interfaces can be implemented on your own
custom classes and structures to define types that integrate tightly within the framework.
Interface Types vs. Abstract Base Classes
Given your work in Chapter 6, the interface type might seem very similar to an abstract base class. Recall
that when a class is marked as abstract, it may define any number of abstract members to provide a
polymorphic interface to all derived types. However, even when a class does define a set of abstract
members, it is also free to define any number of constructors, field data, nonabstract members (with
implementation), and so on. Interfaces, on the other hand, contain only abstract member definitions.
The polymorphic interface established by an abstract parent class suffers from one major limitation
in that only derived types support the members defined by the abstract parent. However, in larger
software systems, it is very common to develop multiple class hierarchies that have no common parent
beyond System.Object. Given that abstract members in an abstract base class apply only to derived
types, we have no way to configure types in different hierarchies to support the same polymorphic
interface. By way of example, assume you have defined the following abstract class:
public abstract class CloneableType
{
// Only derived types can support this
// "polymorphic interface." Classes in other
// hierarchies have no access to this abstract
// member.
public abstract object Clone();
}
Given this definition, only members that extend CloneableType are able to support the Clone()
method. If you create a new set of classes that do not extend this base class, you can’t gain this
polymorphic interface. Also, you might recall that C# does not support multiple inheritance for classes.
Therefore, if you wanted to create a MiniVan that is-a Car and is-a CloneableType, you are unable to do so:
282