Method that returns either SqlConnection or MySqlConnection

Viewed 104

I want to create a method that based on the provider that I'm passing either MySql or MSSQL I would like to return a SqlConnection or a MySqlConnection.

Basically something like this:

public Connection GetConnection(provider) {

   switch (provider) {
      case MSSQL:
         return new SqlConnection(connectionString);
      case MySql:
          return new MySqlConnection(connectionString);
      default:
          return null;
}

Since they are different types I thought about creating an abstract class, something like.

public abstract class BaseSqlConnection
{
    public abstract void Open();
}

public class MSSQLServerConnection : BaseSqlConnection
{
    public MSSQLServerConnection(SqlConnection connection)
    {
        Connection = connection;
    }

    public SqlConnection Connection { get; set; }

    public override void Open()
    {
        Connection.Open();
    }
}

Problem is this is not enough, because I would also need to implement methods like CreateCommand() and others that I might need, so I would like to ask if there is any of you with an easier solution.

1 Answers

Since both objects inherit from the same base class, DbConnection, you can do this:

public DbConnection GetConnection(provider) {

   switch (provider) {
      case MSSQL:
         return new SqlConnection(connectionString);
      case MySql:
          return new MySqlConnection(connectionString);
      default:
          return null;
}

Note you may need to add using System.Data.Common;

Edit:

To incorporate Jon's suggestion, it would look like this:

public DbConnection GetConnection(string provider) => 
    provider switch
    {
        MSSQL => new SqlConnection(connectionString),
        MySql => new MySqlConnection(connectionString),
        _ => throw new ArgumentException("Unknown provider", nameof(provider))
    };
Related