473,408 Members | 1,840 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,408 software developers and data experts.

Casting Problems with dreived classes - is there a general rule?

Hi all,

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? Is there a general rule of thumb?
regards,

Mac

--
Message posted via http://www.dotnetmonster.com
Nov 17 '05 #1
5 1645

"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
Nov 17 '05 #2
You can cast an object of type A to type B if the runtime type of the
object is B or a class derived from B. So in your case, you can cast
the tab page to MyTabPage if the tab page's runtime type is MyTabPage
or one of its subclasses. The question is: how did you use MyTabPage in
your app? Did the collection contain MyTabPage objects, or objects of
the .NET provided TabPage class?
----
Thi - http://thith.blogspot.com

Nov 17 '05 #3
Bjorn & Thi - thanks for your replies.

I managed to get around the error by not actually casting but drectly
assigning instance of MyTabPage = Current TabPage (in the collection).

But looking at the base tabpage definition I realised what you mentioned Thi -
the collection I loop through is a collection of TabPages not of MyTabPage.
So what I assume is happening even though I create a new MyTabPage and set
the properties, they are lost when I add it to a collection of TabPages.

Is there an easy way to create a collection in a TabControl that holds a
derived class of TabPage? The Add function for the TabPageCollection is not
overiddable so I assume this is not possible.

What I am actually trying to do is have a tabcontrol on a MDI container form
where each tabpage represents a open MDI form (I know sounds a bit crude -
but I am unsure how else to achieve this). The properties I am adding to
MyTabPage are to help uniquely identify each form.

Any other design ideas would be appreciated also.
regards,

Mac

--
Message posted via DotNetMonster.com
http://www.dotnetmonster.com/Uwe/For...sharp/200511/1
Nov 17 '05 #4
Hi Mac,
I managed to get around the error by not actually casting but drectly
assigning instance of MyTabPage = Current TabPage (in the collection). Isn't that raise a compile-time error?
But looking at the base tabpage definition I realised what you mentioned Thi -
the collection I loop through is a collection of TabPages not of MyTabPage.
So what I assume is happening even though I create a new MyTabPage and set
the properties, they are lost when I add it to a collection of TabPages. No, nothing is lost. Maybe the VS.NET designer adds some tab pages for
you? And it add TabPage instead of MyTabPage.
If you only add instances of MyTabPage to your collection, it should
work.
Is there an easy way to create a collection in a TabControl that holds a
derived class of TabPage? The Add function for the TabPageCollection is not
overiddable so I assume this is not possible.

The Add function takes a param of type TabPage and that is good. You
don't need to override it. Just call TabPageCollection.Add(new
MyTabPage()). You might want to search your code, especially the code
generated by the VS.NET designer, to make sure there is no code similar
to TabPageCollection.Add(new TabPage()).

Regard,
Thi - http://thith.blogspot.com

Nov 17 '05 #5

"Mac via DotNetMonster.com" wrote...
So what I assume is happening even though I create
a new MyTabPage and set the properties, they are lost
when I add it to a collection of TabPages.
Nope, as I said, the instance itself is *still* a MyTabPage, but you can't
"reach" those properties unless you cast it to a *reference* of MyTabPage.

You could say that the "reference" can't allow you to do anything on a
specific reference than what the type of the reference is.
Is there an easy way to create a collection in a TabControl
that holds a derived class of TabPage?¨
You can add *any* instance from any derived class to it, as ther *are*
TabPages.
The Add function for the TabPageCollection is not
overiddable so I assume this is not possible.


And not necessary...

If you instantiated the TabPages as MyTabPages from the start, that wouldn't
be any problem, other than you need to "cast" it again when you fetch the
TabPages out of the Collection.

As I said, you *can* cast to references of a type that the instance really
*is*, and as a MyTabPage *is-a* TabPage, that wouldn't be any problem.

I think the problem here lies a tad in that you maybe rely to much on the
GUI editor?

If you add "ordinary" TabPages through the GUI editor, you can then go into
the source for InitializeComponent and simply change all...

new System.Windows.Forms.TabPage();

....to...

new MyTabPage();

And, as I said, when you want to actually make use of the special properties
you've added, you need to cast to such a reference. Example:

MyTabPage x = (MyTabPage) this.tabControl1.SelectedTab;

...and...

MyTabPage y = (MyTabPage) this.tabControl1.TabPages[2];

....is completely valid as long as the pages added to the collection *really*
are instances of MyTabPage.

Hope this helps.

// Bjorn A


Nov 17 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: LRW | last post by:
Below I'll paste my CSS and the HTML in question. But what's happening is, I'm trying to establish a link behavior for a class that's separate from the normal link class. I've established a: 's...
4
by: Jacob Jensen | last post by:
This question has probably been asked a million time, but here it comes again. I want to learn the difference between the three type cast operators: static_cast, reinterpret_cast, dynamic_cast. A...
3
by: Andy Lomax | last post by:
I'm using a library where the supplier has provided base class 'foo', and a reference counting class which wraps 'foo': ------------------- library code ----------------------- template<class T>...
35
by: ytrama | last post by:
Hi, I have read in one of old posting that don't cast of pointer which is returned by the malloc. I would like to know the reason. Thanks in advance, YTR
2
by: philippe sillon | last post by:
Hi, I have a problem to implemente the strategy pattern. the problem come from that a method take different arguments type (object in interface and String / Int in implemented class). When...
1
by: Remco | last post by:
Hi, Let me try to simply explain my questions. I've created a portal site with different types of users, e.g. Portal Administrators and Normal Users. One base class SessionUser (has a enum...
2
by: DaTurk | last post by:
I have three interfaces, lets call them General, Client, Server. public interface General { public Value{get;} } public interface Client : General {}
7
by: S. Lorétan | last post by:
Hi guys, Sorry for this stupid question, but I don't know why it isn't working. Here is my (example) code: namespace Test { class A { public string Label1; }
19
by: dl | last post by:
I'll try to clarify the cryptic subject line. Let's say I have a base class 'GeometricObject' with a virtual method 'double distance (const GeometricObject &) const'. Among the derived classes...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.