Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Override generic method using class generic parameter

Tags:

c#

generics

Why is this not possible?

abstract class A
{
    public abstract T f<T>();
}

class B<T> : A
{
    public override T f()
    {
        return default (T);
    }
}

Errors:

does not implement inherited abstract member 'A.f<T>()'
no suitable method found to override

I know that the signature must be same, but from my point of view I see no reason what could possibly be wrong that this is forbidden. Also I know that another solution is to make A generic, rather than its method, but it is not suitable for me for some reason.

like image 440
Zoka Avatar asked Dec 26 '22 11:12

Zoka


2 Answers

This is not possible because those methods have different signatures. A.f is generic method and B.f is not (it merely uses class generic argument).

You can see this form caller perspective:

A variableA = new A();
variableA.f<int>();

B<int> variableB = new B<int>();
variableB.f();
like image 67
Rafal Avatar answered Feb 15 '23 16:02

Rafal


B does not fulfil the contract of A.

A allows f to be called with any type parameter to return that type. B doesn't allow f to be called with a type parameter, and just returns the type of B's type parameter.

For example, say you had a B<int> and cast it to an A (which should be possible as it inherits from it). Then you called f<bool>() on it (which should be possible as it's an A). What then? The underlying B<int> doesn't have a method to call.

B b = new B<int>();
// This is legal as B inherits from A
A a = b;
// This is a legal call, but how does b handle it?
bool result = a.f<bool>();
like image 25
Rawling Avatar answered Feb 15 '23 14:02

Rawling