- Home /
How do I call a method in derived class?
Lets say I have some inheritance going on; I have a "Base" class and a "Derived" class.
public Base obj;
...
...
...
obj = new Derived();
obj.SomeMethod(<parameters>);
SomeMethod exists in both classes, but takes different parameters. I want to call the derived SomeMethod for obj.
I'm trying to implement something that uses this and can't get it to work : ( "No overload for method SomeMethod takes 2 arguments". It looks like the method in the derived class can't be seen at all.
Answer by Waz · Aug 01, 2011 at 07:27 PM
Correct, it cannot be seen since obj is a Base. Just because you know it is a Derived does not allow you to call subclass methods. Binding is static, not dynamic. You must assert your knowledge with a downcast:
(obj as Derived).SomeMethod(...);
If you do this a lot, I would suggest that obj be private Derived and that the public interface be a getter that returns it as a Base.