Reputation: 920
Rather than maintaining a few different database access layers for OleDbConnection, MySqlConnection, OdbcConnection, and Db2Connection, I was trying to figure out a way to use generics. However, I get an error when I try to compile the code, I get errors when I try to access the class's methods or properties.
public class DatabaseConnector<CONNECTION> {
private CONNECTION connection = default(CONNECTION);
public bool IsConnected {
get {
return (
this.connection != null &&
// error on connection.State on the following two lines
this.connection.State != System.Data.ConnectionState.Closed &&
this.connection.State != System.Data.ConnectionState.Broken
);
}
}
}
Is there any way around this? Or perhaps another class that can handle the many versions?
Upvotes: 0
Views: 171
Reputation: 920
That fixed it! It never occurred to me to use interfaces.
public class DatabaseConnector<CN, TRANS, CMD, DA, PARAM>
where CN:IDbConnection
where TRANS:IDbTransaction
where CMD:IDbCommand
where DA:IDbDataAdapter
where PARAM:IDbDataParameter
Upvotes: 0
Reputation: 186
Try to use the where
in your class definition:
class DatabaseConnector<CONNECTION> where CONNECTION: DbConnection
Like this you will be able to use the methods defined in the common class.
you will need after that to make a similar class for command and all the other functions that you need.
Upvotes: 1
Reputation: 888273
You're looking for constraints:
public class DatabaseConnector<TConnection> where TConnection : DbConnection, new() {
Upvotes: 5