Why should I use interface?

  • Thread starter Thread starter Marius Horak
  • Start date Start date
To gurantee that there is certain methods implemented ie., an interface.

IEnumerable is an interface, with out it you would not have Foreach loop
constructs.
 
Cannot see any good reason for using it (just duplication of
code.). Can you?

Marius,

I'm sure you've familiar with object inheritance, sometimes known as
"vertical" inheritance. On a taxonomy chart of classes, a child
class descends from a parent class. That means the child class
appears below the parent class on the chart, hence the "vertical"
inheritance.

Interfaces allow for "horizontal" inheritance. Two or more classes
which do not have a vertical relationship may be related via
interfaces.

Here's a good example of the usefulness of interfaces. Suppose you
need to write a single method that will return a data reader for
either an OleDB data source (OleDbDataReader), or an MS SQL Server
data source (SqlDataReader).

Note that neither of these objects have a useful common "data
reader"-type parent. They both descend from MarshalByRefObject,
which is too generic to be useful here as a return type.

So we can't have the method's signature look like any of these:

public OleDbDataReader GetDataReader()
public SqlDataReader GetDataReader()
public MarshalByRefObject GetDataReader()

The last one would almost work, but the caller would have to downcast
to either OleDbDataReader or SqlDataReader. The problem is the
caller would not know which one to downcast to!

The solution is to use the IDataReader interface. Even
though OleDbDataReader and SqlDataReader aren't related "vertically",
the are related "horizontally" because they both implement the
IDataReader interface. The method signature becomes:

public IDataReader GetDataReader()

The caller can use the method like this:

IDataReader dr = GetDataReader();

while (dr.Read())
{
// Process rows here.
}

GetDataReader() could return either a OleDbDataReader or
SqlDataReader. The caller's code stays the same since it only cares
about the returned interface, and not the returned object's type.

Hope this helps.

Chris.
 
Back
Top