Arik Shapiro
Arik Shapiro

Reputation: 33

How do I accomplish the following with C# generics?

I have a generic Result<T> class and let's assume I have a Handler<TRequest, TResponse> interface and I want TResponse to be of type Result<T>.

how can implement the interface so it is close to the following example:

class HandlerImp<TRequest, TResponse> 
: Handler<TRequest, TResponse>
 where TRequest : Result<T>

the reason I want to be able to do this is I want to be able to return new Result<T> in the handler and I can not do that without knowing what the result type is.

Upvotes: 0

Views: 680

Answers (1)

Arik Shapiro
Arik Shapiro

Reputation: 33

I've managed to solve my problem in the following way:

    class Result
    {
        public IList<string> Errors { get; set; }
        public Exception Exception { get; set; }
    }

    class Result<T> : Result
    {
        public T Data { get; set; }
    }

    interface IHandler<TRequest, TResponse>
    {
        TResponse Handle();
    }

    class HandlerImp<TRequest, TResponse> : IHandler<TRequest, TResponse>
        where TResponse : Result, new()
    {
        public TResponse Handle()
        {
            return new TResponse()
            {
                Errors = new List<string>() { "This is an error" }
            };
        }
    }

It does not let me put the T Data but for my use case (ValidationHandler) it's great.

Upvotes: 1

Related Questions