Tomtom
Tomtom

Reputation: 9384

Inherit from Interface in generic class

I have the following class:

public class DataInterop <T> where T : ITableAdapter
{
   private ITableAdapter tableAdapter;

   public DataInterop(T tableAdapter)
   {
      this.tableAdapter = tableAdapter;
   }
}

In the ITableAdapter-Interface are Methods defined like Read(), Write(...), Update(...), Delete(...), ...

Now I want the Class DataInterop to have all Methods from the ITableAdapter interface.

Is it possible for a generic-class to inherit from an interface?

Upvotes: 1

Views: 278

Answers (3)

Matthew Watson
Matthew Watson

Reputation: 109537

You just need to add : ITableAdaper after the DataInterop<T>

public class DataInterop<T>: ITableAdapter where T: ITableAdapter
{
    private ITableAdapter tableAdapter;

    public DataInterop(T tableAdapter)
    {
        this.tableAdapter = tableAdapter;
    }
}

(It looks like you're implementing an Adapter Pattern or a Decorator Pattern.)

Upvotes: 3

Rohit Vats
Rohit Vats

Reputation: 81233

Ofcourse you can. Sample layout -

public interface IBar
{ 
    string Name { get; set; }
}
public class Foo<T> : IBar
{
    public string Name { get; set; }
}

Upvotes: 1

mnkypete
mnkypete

Reputation: 329

Yes it is possible, it's especially useful when you handle instances of the class without knowing the concrete type at runtime.

The syntax would be:

public class DataInterop <T> : ITableAdapter where T : ITableAdapter 

Upvotes: 2

Related Questions