tags:

views:

119

answers:

2

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.

+11  A: 

Use IDbConnection - that is common to both types.

SqlConnection inherits from DbConnection which in turn implements the IDbConnection interface. This interface is also implemented by AdomdConnection.

Therefore you can use the IDbConnection interface to represent both types

Andrew Hare
Just to flesh this correct answer out for the OP, SqlConnection inherits from and abstract class DBConnection which implements IDbConnection.
JP Alioto
Thanks to all for answers - Just out of interest, if there wasn't a common interface that could passed but there were common methods how could that be wrapped?
DaHollsta
You would wrap it much in the same way you showed in your question.
Andrew Hare
+2  A: 

SqlConnection is constructed from: DbConnection, ICloneable.

Yes, it is, but DBConnection itself extends and implements Component, IDbConnection, IDisposable

So you could handle both objects as IDbConnection

Eoin Campbell