x


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.

more ▼

asked Aug 01 '11 at 06:33 PM

crump3ts gravatar image

crump3ts
1 5 5 6

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

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.

more ▼

answered Aug 01 '11 at 07:27 PM

Waz gravatar image

Waz
6.4k 22 33 71

Thank you! : 3

Aug 01 '11 at 09:23 PM crump3ts
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x134
x40
x18
x12

asked: Aug 01 '11 at 06:33 PM

Seen: 950 times

Last Updated: Aug 01 '11 at 09:23 PM