Jeroen de Jong
Jeroen de Jong

Reputation: 11

Adding an Extension Method to a Generic class

How can i create a extension of my Container class? without testing the DB Type.

public abstract class DBAccess : IDBAccess, IDisposable
{
}

public class DB1 : DBAccess
{
}

public class DB2 : DBAccess
{
}

public partial class TAContainer<T> : TableAdapterModel<T, DTContainer>, ITAContainer
    where T : DBAccess, new()
{
}

Now my extension would like something

public static int ExecuteByExtension(this ITAContainer tAContainer, IDTContainer dataTable)
{
    var ta = (tAContainer as TableAdapter<DB1>);


}

This all works. But i would like to set the variable ta to the abstract class "DBAccess". This cannot be done, also using a interface is not possible.

How to use a single Type for the casting. and not testing for DB1 or DB2

the result should be called like:

var dataTable = new DTContainer() as IDTContainer;
var container = new TAContainer<DB1>() as ITAContainer;
int result = container.ExecuteByExtension(datatable);

Upvotes: 1

Views: 110

Answers (1)

Glenn Ferrie
Glenn Ferrie

Reputation: 10390

Could you just add the generic argument to your extension method, like this:

public static int ExecuteByExtension<T>(
     this TAContainer<T> tAContainer, IDTContainer dataTable) where T : DBAccess, new()
{
    var ta = (tAContainer as TableAdapter<T>);
    // ...
    return 0;
}

Upvotes: 2

Related Questions