Let's say I have two classes called "Thing" and "Thang" that both inherit from "Widget". I know that the base class of Thing and Thang is a Widget, but when I'm using a reference to one from another class, I don't know which one I'm currently using. Let's also say that Thing and Thang both have a function that has the same name, but have to be defined within, and executed from, the derived class (Thing or Thang) for one reason or another.
Here is what I know:
1) The name of the function I need to call.
2) The parameters I need to pass to the function.
Here's what I don't know
1) Whether I'm currently calling this function on Thing or Thang (so I can't just cast to the right type and call the function)
What I would like to know is this... Is there any way to call the function on Thing or Thang (regardless of which one it is because I have a reference to the exact object, I just don't know which type it is) without knowing the type?
I know that I could just do a GetType() on my reference and use some not-so-clever conditionals, but this is very messy and will require a lot of maintenance as I continue to subclass Widget. Any other options?
Thanks,
Joshua Foulk
Joshua FoulkPosted Jan 27, 2009, 12:32 AM
Carl,
Thank you for your reply. As it happens, Widget is not a class that I created, it's a base system class (UserControl in Silverlight) and I don't care to subclass from it just to make this method available in this situation. I posed this question on another forum and was given a very excellent idea. One of those suggestions that reminds me how simple some problems really are.
I'm going to create an interface "IWidget" for Thing and Thang that will force them to implement my method, and I can simply cast them as an IWidget and call the method that way.
Duh! lol
Joshua Foulk
Carl SchraderPosted Jan 26, 2009, 10:18 PM
Joshua,
Is there a reason you are not making the function virtual in the Widget class (base) and overriding the function in the Thing/Thang classes? If you need to do something specific for the Thing/Thang objects, do it in the overriden version of the function. If you need to do something on both of the objects, you can flesh out the details in the base (Widget) version of the function and call base.() in the Thing/Thang overriden versions of the function.
Please supply me with some more details if the above is incorrect and I will be happy to help you out.
Carl