rbasniak
rbasniak

Reputation: 4964

Overriding abstract method with the inherited class as parameter type

I have an abstract class like this:

public abstract class BaseClass
{
    ...

    public abstract void MyMethod<T>(T value);
}

In the inherited classes I want to pass the type of the class itself as the parameter T, so I tried to do this:

public class InheritedClass: BaseClass
{
    ...

    public override void MyMethod<InheritedClass>(InheritedClass value)
    {
        ...
    }
}

But intellisense is warning me that 'Type parameter InheritedClass hides class Inherited class'

What does this message exactly mean? Is there any other way to achieve this?

Upvotes: 0

Views: 1396

Answers (1)

juharr
juharr

Reputation: 32266

The error is because your method is creating a generic type with the same name as the class. You cannot specify the generic type for a method when defining it, only when calling it.

Only way to achieve that is to define the generic type on the class so you can specify it when you inherit.

public abstract class BaseClass<T>
{
    public abstract void MyMethod(T value);
}

public class InheritedClass: BaseClass<InheritedClass>
{
    public override void MyMethod(InheritedClass value)
    {
    }
}

Upvotes: 1

Related Questions