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.
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();
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>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With