Generic type access property not defined in the interface by using dynamic

advertisements

I'm having to modify a lot of code to set a SqlCe database connection for a bunch of table adapters. I would like to avoid the duplication involved and minimise the chance I've missed updating a table adapter by creating a generic method to wrap the creation of each table adapter. Unfortunately the table adapters aren't derived from a single base class and each has it's own Connection property. By assigning the new table adapter to dynamic I can get it to compile. Is this a good approach and are there any traps I should be aware of when using dynamic?

protected void TableAdapter<T>(Action<T> action) where T : IDisposable, new()
{
    using (var connection = new SqlCeConnection(ConnectionString))
    using (dynamic tableAdapter = new T())
    {
        tableAdapter.Connection = connection;
        action(tableAdapter);
    }
}


Nah, no traps. I think you are exchanging a compiler check for improved readability. And if someone else uses it wrong the runtime error will be obvious that the Connection member isn't there.

Personally, I would also add the cast to the argument of the action, because the dynamic invocation there shouldn't be necessary. But i consider that an optional choice because the performance gain is probably negligible, it's going to work the same either way, my person style is to limit the scope of dynamic use to purposeful.

protected void TableAdapter<T>(Action<T> action) where T : IDisposable, new()
{
    using (var connection = new SqlCeConnection(ConnectionString))
    using (dynamic tableAdapter = new T())
    {
        tableAdapter.Connection = connection;
        action((T)tableAdapter);
    }
}