Robotronx
Robotronx

Reputation: 1818

Cannot return `this` from overridden base class method

I cannot return a this from a concrete method implementation, even though the signatures are all appropriate. The idea here is to have a fluent builder, so subclassed BuildNewCar() needs to return subclass type SimpleCarBuilder.

public class Car {}

abstract class BaseCarBuilder
{
    public abstract T BuildNewCar<T>();
}

class SimpleCarBuilder : BaseCarBuilder
{
    Car _car;

    public override SimpleCarBuilder BuildNewCar<SimpleCarBuilder>()
    {
        _car = new Car();
        return this;
    }
}

I keep getting:

Cannot implicitly convert type 'SimpleCarBuilder' to 'SimpleCarBuilder'

Upvotes: 0

Views: 43

Answers (1)

Grax32
Grax32

Reputation: 4069

The compiler is seeing SimpleCarBuilder as the name of your generic type, not as the actual type to use. It can't convert actual type SimpleCarBuilder to a generic type parameter named SimpleCarBuilder that could actually represent any type.

If you use the implement abstract class feature, you'll see that the compiler uses T as the generic type parameter name.

Upvotes: 2

Related Questions