Danny Lau
Danny Lau

Reputation: 21

C# Return generic class from method

Here is my code below, with unimportant parts redacted:

public class Response<T>
{
    //...
}

public class Summary
{
    //...
}

public class Db : IDb
{
    public Response<Summary> Generate()
    {
        //...
        return new Response<Summary>
        {
            //...
        };
    }

    public Response<Summary> Execute<Summary>()
    {
        return Generate();
    }
}

I get an error that says: Cannot implicitly convert type Response<Service.Models.Summary> to Response<Summary>.

Am I using generics wrong? Basically, I am expecting to see a Response model when I call the method Generate(), and in this instance T is the Summary class.


The interface I'm implementing is this:

public interface IDb
{
    Response<T> Execute<T>();
}

Upvotes: 0

Views: 162

Answers (1)

Enigmativity
Enigmativity

Reputation: 117029

Your method public Response<Summary> Execute<Summary>() has a generic parameter of Summary that is overriding the class definition of Summary. The return type of Response<Summary> in Execute<Summary>() is a different type than the return in Generate().

It seems likely that you code should be:

public Response<Summary> Generate()
{
    //...
    return new Response<Summary>
    {
        //...
    };
}

public Response<Summary> Execute()
{
    return Generate();
}

Given the addition of your interface IDb then the above answer doesn't work.

You must implement Execute as public Response<T> Execute<T>() and that means that the return type Response<T> is not the same as Response<Summary> at compile-time. So the error is correct.

You basically now have a design flaw.

It's likely that you need to make this change:

public class Db : IDb<Summary>
{
    public Response<Summary> Generate()
    {
        //...
        return new Response<Summary>
        {
            //...
        };
    }

    public Response<Summary> Execute()
    {
        return Generate();
    }
}

public interface IDb<T>
{
    Response<T> Execute();
}

Upvotes: 3

Related Questions