mike01010
mike01010

Reputation: 6038

Overriding a virtual method with a generic return type

Consider these two abstract classes. MyClass2 extends my BaseClass and overrides a virtual method. Note it also defines TValue of MyBaseClass as IList...

public abstract class MyBaseClass<TKey, TValue>
{
    public virtual IList<TValue> DoSomeStuff()
    {
        IList<TValue> result;
        ....
        return restult;
    }
}

public abstract class MyClass2<TKey, TValue>: MyBaseClass<TKey, IList<TValue>>
{
    public override IList<TValue> DoSomeStuff()
    {
        IList<TValue> result;
        ....
        return restult;
    }
}

This code does not compile. The complaint is on the return type of MyClass2.DoSomeStuff. The error is "Cannot change return type when overriding method "IList<TValue> MyClass2<TKey, TValue>.DoSomeStuff()"

I'm not clear as to why this is wrong. Why wouldn't the compile or .net consider TValue for the overriden method to be that of MyClass2?

Upvotes: 0

Views: 1272

Answers (3)

Ry-
Ry-

Reputation: 224904

The problem's in your base class part:

public abstract class MyClass2<TKey, TValue>: MyBaseClass<TKey, IList<TValue>>

Replace the IList<TValue> with TValue and it will work - the method already returns an IList.

Upvotes: 3

Justin Niessner
Justin Niessner

Reputation: 245419

You're getting the error because TValue in the child class is actually IList<TValue> in the base class so the method signature (as your base class would see it) would be IList<IList<TValue>> which obviously doesn't match the virtual method's signature.

To get matching types, you would have to change the signature:

public override TValue DoSomeStuff()
{
    TValue result;

    return result;
}

Upvotes: 1

BoltClock
BoltClock

Reputation: 723568

The TValue parameter of your base class, as inherited by your subclass, is actually IList<TValue> as declared by your subclass. The inner TValue pertains to your subclass.

So if you're trying to override the existing virtual method that belongs to the base class, the return type is actually expected to be IList<IList<TValue>>; that is, an IList of the TValue that belongs to your base class, not the subclass.

Upvotes: 3

Related Questions