2

I have a Response class with two constructors. One receive a Result object and other a generic Result object.

How to declare the generic constructor of Response class to get the generic object?

In this sample code, the non-generic constructor is used.

var result = new Result<SomeModel>();
var response = new Response(result); // should use the generic constructor but uses the normal

public interface IModel
{
}

public class SomeModel : IModel
{
    public string Text { get; set; }
}

public class Result<T> : Result where T : class, IModel
{
    public T Model { get; set; }
}

public class Result
{
    public bool Success { get; set; }
}

public class Response
{
    public Response(Result<IModel> data)
    {
    }

    public Response(Result data)
    {
    }
}
Max Bündchen
  • 1,283
  • 17
  • 38

1 Answers1

3

A Result<IModel> isn't the same as a Result<SomeModel>.

You have two options: first, you can make Response generic as Response<T> where T : IModel and then change the constructor to take a Result<T>.

Alternately, you can define an IResult<out T> interface (implemented by Result<T> with only a getter for the model property, and change the constructor of Response to take an IResult<IModel>; this is called "covariance".

ekolis
  • 6,270
  • 12
  • 50
  • 101