Reputation: 81
Here's the c# code I'm trying to compile
Fairly simple, testDMO
that inherits from testDMOBase
Then test that inherits from testBase
public abstract class testDMOBase { }
public class testDMO : testDMOBase { }
public abstract class testBase
{
abstract protected void LoadCRUD(testDMOBase dmo);
}
public class test : testBase
{
override protected void LoadCRUD(testDMO dmo) { }
}
I'm getting the following errors:
'test' does not implement inherited abstract member 'testBase.LoadCRUD(testDMOBase)' 'test.LoadCRUD(testDMO)': no suitable method found to override
Shouldn't the use of a subclass be ok on the override method?
Upvotes: 2
Views: 4903
Reputation: 101700
Shouldn't the use of a subclass be ok on the override method?
No, method overrides must use the same parameter types as their original declarations.
Upvotes: 0
Reputation: 1501043
Shouldn't the use of a subclass be ok on the override method?
No. Aside from anything else, which implementation would you expect to be called if the caller provided an instance other than your subclass?
testBase t = new test();
t.LoadCRUD(new SomeOtherDMO()); // What would be called here?
You might well argue that it would make sense to be able to override the base method with a subclass method which is more general (e.g. with a parameter which is a superclass of the original parameter type, or with a return type which is a subclass of the original return type) but .NET doesn't allow either of these anyway. The parameter and return types of the overriding method have to match the original method exactly, at least after generic type parameter substitution.
It sounds like you may want to make your base type generic:
public abstract class TestBase<T> where T : TestDmoBase
{
public abstract void LoadCrud(T dmo);
}
public class Test : TestBase<TestDmo>
{
public override void LoadCrud(TestDmo dmo)
{
...
}
}
Note that you should follow .NET naming conventions, too - even in sample code.
Upvotes: 5
Reputation: 62266
No, in this case you have to exactly follow the signature of the abstract
method, in order to provide valid override.
So, you have to write:
public class test : testBase
{
override protected void LoadCRUD(testDMOBase dmo) //BASE CLASS
{ }
}
Upvotes: 4