I am working with SqlConnection and AdomdConnection objects in C#.
SqlConnection is constructed from: DbConnection, ICloneable.
AdomdConnection is constructed from: Component, IDbConnection, IDisposable, ICloneable.
I hoped I could use a common interface or class type to pass around but that doesn’t seem to be an option because they don’t share a common type, that I can tell.
They both have similar methods that I need to call but as I am going to write some logic around calling them for either I wanted to wrap them into their own class and then just call that class and let it worry about the underlying type.
Initially, I thought I could use something like this:
public class ConnectionWrapper {
protected object _Conn;
public ConnectionWrapper(object Conn) {
_Conn = Conn;
}
public void Open() {
if (_Conn is SqlConnection) {
((SqlConnection) _Conn).Open();
} else if (_Conn is AdomdConnection) {
((AdomdConnection) _Conn).Open();
}
}
}
But I can’t help but wonder that there isn’t a better way to do it.
I came across the TypeMap class (see question 298976) which would be a more readable way to do it, but I couldn’t figure out how to use return values with that, but still wonder if there is a better way to do it.
Use
IDbConnection– that is common to both types.SqlConnectioninherits fromDbConnectionwhich in turn implements theIDbConnectioninterface. This interface is also implemented byAdomdConnection.Therefore you can use the
IDbConnectioninterface to represent both types