"Mac via DotNetMonster.com" wrote...
I have a creating a my own tabpage class (MyTabPage) which
inherits the .Net TabPage class.
In the relevant event I want to loop through the
collection of TabPages and
then when I find the TabPage I am after I want to cast
this to MyTabPage so that I can access the properties
that I have added to this class.
When I try to do this I get an "invalid cast"
error at runtime. Am I not able to cast from
a baseclass to a derived class?
You cannot "cast" an object at all, what you can do is to change the type of
reference to it.
However, you can only change that type to anything the object really *is*
from the point you instantiated it.
Example:
MyTabPage x = new MyTabPage();
Now you have a reference of type 'MyTabPage' to the object.
TabPage y = (TabPage) x;
Now you have another reference to the same object, but of type 'TabPage'.
That is possible since any instance of 'MyTabPage' *is-a* 'TabPage', through
inheritance.
If you look on inheritance as an inheritance tree, the *lowest* you can cast
to is, the actual type you used at instantiation.
But you can also cast to any type that is higher in the tree in the same
line of heritage, e.g.
Panel z = (Panel) x;
You can also cast to (most) any interface type any of those classes has
inherited, e.g.
IComponent p = (IComponent) x;
Note, the instance itself couldn't care less, as it's *still* an instance of
'MyTabPage' in this case. It hasn't "become" an instance of another type,
but you now got a couple of *references* of other types to it.
So, the "solution" to your problem, is to simply instantiate those objects
*as* instances of 'MyTabPage' in the first place...
// Bjorn A