I have a function that would love to take advantage of the "correct" way to do something that was provided in .NET 4.5:
public DbDataAdapater CreateDataAdapter(DbConnection connection)
{
#IFDEF (NET45)
return DbProviderFactories.GetFactory(connection).CreateDataAdapter();
#ELSE
//We can't construct an adapter directly
//So let's run around the block 3 times, before potentially crashing
DbDataAdapter adapter;
if (connection is System.Data.SqlClient.SqlConnection)
return new System.Data.SqlClient.SqlDataAdapter();
if (connection is System.Data.OleDb.OleDbConnection)
return new System.Data.OleDb.OleDbDataAdapter();
if (connection is System.Data.Odbc.OdbcConnection)
return new System.Data.Odbc.OdbcDataAdapter();
//Add more DbConnection kinds as they become invented
if (connection is SqlCeConnection)
return new SqlCeDataAdapter();
if (connection is MySqlConnection)
return new MySqlDataAdapter();
if (connection is DB2Connection)
return new DB2DataAdapter();
throw new Exception("[CreateDataAdapter] Unknown DbConnection type: " + connection.GetType().FullName);
#END
}
The only way i've been able to find to make this work is for everyone who uses this shared code to alter their Visual Studio solution.
Which not going to happen; it has to just work, or it's not going to be used at all.
Is there a ways to define away non-functional code when the solution targets earlier versions of the .NET framework?
In other words, it would be great if this compiled:
public DbDataAdapter CreateDataAdapter(DbConnection conn)
{
if (System.Runtime.Version >= 45)
return DbProviderFactories.GetFactor(connection).CreateDataAdapter();
else
{
//...snip the hack...
}
}
But it doesn't compile if the targeted framework is too low.