I find that I've written the same code twice. There's this, with DataSet
public static DataSet foo(SqlCommand)
{
var Adaptor = new SqlDataAdapter(Command);
// The important line:
DataSet Output = new DataSet();
Adaptor.Fill(Output);
return(Output)
}
and this with DataTable
public static DataTable foo(SqlCommand)
{
var Adaptor = new SqlDataAdapter(Command);
// The important line:
DataTable Output = new DataTable();
Adaptor.Fill(Output);
return(Output)
}
Is there any way to remove this repetition? My attempts with generics have failed, since the compiler can't know that what I'm passing in is always safe to Fill
.
No, this code can't be DRY'd because there's no Fill
overload that takes in an interface or a class that is a common base to both DataSet
and DataTable
.
There's also no way to use generic constraints in the form of or -
You can't have a generic method where T is one of several unrelated types (by related I mean, of course, polymorphic interchangeable) so a attempting to write your method like static T foo<T>(SqlCommand cmd) where T : DataSet or T : DataTable
will not compile.
However, given the fact that these are only four lines of code that's being duplicated, I think it's not really a problem.