RidingTheRails
RidingTheRails

Reputation: 1105

Is it possible to wrap two similar class functions into one class in C#?

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.

Upvotes: 2

Views: 361

Answers (2)

Andrew Hare
Andrew Hare

Reputation: 351506

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

Upvotes: 11

Eoin Campbell
Eoin Campbell

Reputation: 44268

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

Upvotes: 2

Related Questions