Mou Mou - 1 year ago 74
C# Question

C#: Return dynamic sql connection based on T type by generic usage

suppose i am working with many sql connection object. some connect my local db, some connect my remote db etc

public static T GetGenericConnection<T>()


so i want to call a function like
GetGenericConnection<DBLocal>() or GetGenericConnection<DBRemote>()
will return sql connection object as T based on pass value. pass value means few class name like
DBLocal or DBRemote

or i will call function like
GetGenericConnection<ConnectionType.DBLocal>() or GetGenericConnection<ConnectionType.DBRemote>()

is enum type.

function will return
DBLocal or DBRemote
instance as type T based on pass value.

please show me how to achieve this with sample code. thanks


public static T GetGenericConnection<T>(ConnectionType ConnectionFor)
if (ConnectionFor == ConnectionType.LocalSQLConnection)
return (T)Convert.ChangeType((new BBASQLLocalConnection()).Connection, typeof(T));
else if (ConnectionFor == ConnectionType.ORCSWEBSQLConnection)
return (T)Convert.ChangeType((new BBAORCSSQLConnection()).Connection, typeof(T));
else if (ConnectionFor == ConnectionType.ReportConnection)
return (T)Convert.ChangeType((new BBASQLReportConnection()).Connection, typeof(T));
return (T)Convert.ChangeType((new BBASAGEConnection()).Connection, typeof(T));

some kind of problem occur when i call function like this way

SqlConnection conn1 = (SqlConnection) ConnectionManager.Factory.BBADBConnectionFactory.GetGenericConnection<BBASQLLocalConnection>(ConnectionType.LocalSQLConnection);

Error message was

Cannot convert type 'ConnectionManager.BBASQLLocalConnection' to

Answer Source

You don't need a generic type parameter for this. Just a regular argument will do:

public static IDbConnection GetDatabaseConnection(ConnectionType db) 

    switch (db)
        case ConnectionType.DBLocal:
            return new SqlConnection("dblocal connection string here");
        case ConnectionType.DBRemote:
            return new SqlConnection("db remote connection string here");
            throw new InvalidArgumentException("Unrecognized DB Type");

Okay, based on your update I see more of what your problem is; you have wrapper objects for your connection types. What I'm suggesting here is still the correct approach. What changes with the question edit is that you also need to make sure your special connection wrapper types all implement a common interface.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download