Returning a cast object to original type

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
<p dir=ltr style="margin-right:0px How do I return a down-cast object to its original type, if the original type is not set at compile-time?

I have a number of different objects that I am storing in a treeview control. When the user selects a treeview node, the object stored in the nodes Tag property is returned. But it is returned as type object. I need to get the object back to its original type.

Heres my problem: I wont know the original type of the object until it is returned. The object in the node could be any one of a dozen or so types.

I know that I can find the original type of the object using its GetType() method. But how do I cast the object back to that original type, so that I can access its members?

For example, I store a Widget in a treeview nodes Tag property. When the user selects  the node, the widget is returned as a type object. I can use the object.GetType() method to discover that the object is, in fact, a widget. But then how do I up-cast back to the Widget type that I need?

If I knew in advance that I would need a Widget object, then its easy:

Widget myWidget = (Widget)Node.Tag

But I wont know that a Widget is what I need until I get the object out of the Tag property and invoke the object.GetType() method on it. So, what I think I need is the line of code that gets me the Widget object reference that I can cast my widget to.

Thanks in advance for your help!

David Veeneman
Foresight Financial

View the full article
 
Back
Top