user9593650
user9593650

Reputation:

response class with generic <T>

Sorry if this has been asked before, but I can't find it and I'm not exactly sure what to search on.

I've got a generic response class like this:

 public class ResponseModel<T>
{
    public T Data { get; set; }
    public Exception Ex { get; set; }
    public string Message { get; set; }
    public bool Success { get; set; }
}

I'd like to do something like the code below so that I can simply pass the errors up the stack by doing a return retVal.Set<T>(responseModelObject);

    public ResponseModel<T> Set<T>(ResponseModel<T> rm)
    {
        Ex = rm.Ex;
        Message = rm.Message;
        return this;
    }

This works fine if the T class is identical between retVal and responseModelObject, but won't compile if they don't match.

Is there a way to do this or am I just sol?

Upvotes: 1

Views: 3630

Answers (3)

aepot
aepot

Reputation: 4824

You may create an interface

public interface IResponseModel
{
    Exception Ex { get; set; }
    string Message { get; set; }
    bool Success { get; set; }
}

public class ResponseModel<T> : IResponseModel
{
    public T Data { get; set; }
    public Exception Ex { get; set; }
    public string Message { get; set; }
    public bool Success { get; set; }
}

Then the method will look like

public ResponseModel<T> Set(IResponseModel rm)
{
    Ex = rm.Ex;
    Message = rm.Message;
    return this;
}

Also interface will allow you to create collections of IResponseModel which may conrain generics of different types. It maybe also useful with async operations like Task<IResponseModel>, etc.

Upvotes: 1

Dmitry
Dmitry

Reputation: 14059

You could try to declare method as:

public ResponseModel<T> Set<TOther>(ResponseModel<TOther> rm)
{
    Ex = rm.Ex;
    Message = rm.Message;
    return this;
}

Sample usage:

ResponseModel<int> a = new ResponseModel<int>();
ResponseModel<string> b = new ResponseModel<string>();
b.Set(a); // It compiles

Upvotes: 1

Marco
Marco

Reputation: 1093

Is this working ?

public ResponseModel<T,S> Set<S>(ResponseModel<T> rm)
{
    Ex = rm.Ex;
    Message = rm.Message;
    return this;
}

Upvotes: 0

Related Questions