An interface, as the docs say, is a contract. If a class implements an
interface, this means that calling one of the interface methods on the class
will work. It also means that a variable declared as an interface can
contain any object implementing the interface.
For an example, I like the IDbConnection interface. This interface has the
generic methods for connecting to a database such as:
IDbConnection.ConnectionString (property)
IDbConnection.Database (property)
IDbConnection.BeginTransaction()
IDbConnection.Close()
IDbConnection.CreateCommand()
IDbConnection.Open()
In this case, once you have an *instance* of an IDbConnection, you can call
any of these methods to perform some action. IDbConnection is implemented
by OleDbConnection, SqlConnection, MySqlConnection, etc... The benefit is
that this adds a level of indirection or generalization (good) while
maintaining type safety, etc (I think).
In the example above, say, imagine tomorrow your boss says you no longer
want to use SQL as your db, but would rather switch to Access, or MySql, or
whatever. If you declared all your connections as "SqlConnection", you're
stuck rewriting a bunch of code. If you used "IDbConnection" you only have
to change the code where you instantiate the connection. I often do this in
a special, semi-global method like this:
public enum SupportedConnType {Sql, MySql, Access, ...}
class ConnFactory {
public static IDbConnection LoadConn(SupportedConnType ctype) {
switch(ctype)
...
}
}
For me, works like a charm, and except for the actual syntax of the Sql
statement (parameters or no), I can switch db's in the blink of an eye. Of
course, this is only one example, and i have only begun to plumb the depths
of interfaces myself.
hth,
scott
I am trying to understand Interfaces. I've looked at various Dog, Animal
and Shape and Circle examples and I am still murky about interfaces.
I am working on a project where I am using Excel to create graphs, but in a
future I might be using third party graphing library like Dundas instead or
in conjunction with Excel. Since I can't do multiple inheritance (Excel and
Dundas) could I use Interfaces to code the graphing methods? Can someone
show me an example of Interfaces with one or two methods for graphing? Or
is there a better way of coding for both libraries?
Thank you
Peter