-1

Hi Would like to know the use case for the generic interface taking interface as an generic parameter . What can it be used for and what it can solve. I am not able to think of use cases to have interface as an generic parameter rather then the class object.

For Example

public interface IProvideA<T>
{
   T GetAVal(string val);
}

Now created a generic type which takes interface as generic parameter.

public interface  IProvideAlpha<T> where T:IProvideA
{
  T GetAlphaVal(string val);
}

Now if i implement a class which is using the interface taking interface as Generic parameter

public class ImplementProvideAlpha<T>:IProvideAlpha<IProvideA<T>> where T:class
{
}
Dinesh
  • 193
  • 2
  • 14
  • 4
    I don't think `where T:interface` is valid code. – Damien_The_Unbeliever Jul 26 '18 at 10:36
  • Unit of work repository pattern passes a class and creates a irepository interface. Something like this https://stackoverflow.com/questions/19548531/unit-of-work-repository-pattern-the-fall-of-the-business-transaction-concept this is not exactly what you mean but I think Damien is correct and where T:interface is not valid code. – Budyn Jul 26 '18 at 10:38
  • @Damien_The_Unbeliever i mean the interface name IProvideAlpha – Dinesh Jul 26 '18 at 10:40
  • @Budyn I mean where T: IProvideAlpha – Dinesh Jul 26 '18 at 10:41
  • If you typed it wrong, edit your question and correct your typo – Cleptus Jul 26 '18 at 11:32

1 Answers1

0

You can guarantee to implement method parameter types or return type via Interface like this;

public interface IService<TRequest, TResponse> 
    where TRequest : IRequest 
    where TResponse : IResponse
{
    TResponse Execute(TRequest request);
}

public interface IRequest
{
    object Head { get; set; }
    object Body { get; set; }
}

public interface IResponse
{
    string Message { get; set; }
    bool IsErrorOccured { get; set; }
}

public class MyServiceRequest : IRequest
{
    //Interface property implementation here...
}

public class MyServiceResponse : IResponse
{
    //Interface property implementation here...
}

The code below is forced to implement execute like this because of IService generic types;

public class MyService: IService<MyServiceRequest, MyServiceResponse>
{
    public MyServiceResponse Execute(MyServiceRequestrequest request)
    {
        //Bus logic here...
    }
}
ilkerkaran
  • 4,214
  • 3
  • 27
  • 42