Up Casting a Control Collection

T

Trevor

Hi,

I'm trying to write a general function to simply clear a collection of
fields from both a group box and a tab control. Here is what I want my code
to look like:

private void ClearFields(GroupBox groupbox)
{
ClearFields((ControlCollection)groupbox.Controls);
}

private void ClearFields(TabPage pg)
{
ClearFields((ControlCollection)pg.Controls);
}

private void ClearFields(ControlCollection lst)
{
foreach (Control c in lst)
{
if (c.GetType() != typeof(System.Windows.Forms.Button))
{
c.Text = "";
}
}
}
}

However, when I write my code this way I get a runtime error that says I
cannot convert the type TabPageControlCollection to a ControlCollection.
TabPageControlCollection is a derived class of ControlCollection. What is it
that I'm not understanding about casting?
 
P

Peter Duniho

[...]
However, when I write my code this way I get a runtime error that says I
cannot convert the type TabPageControlCollection to a ControlCollection.
TabPageControlCollection is a derived class of ControlCollection. What
is it
that I'm not understanding about casting?

I'm not sure. The code doesn't look obviously wrong to me.

That said, there should be no need for an explicit cast. The upcast
should happen automatically, assuming you're actually using the right
types for the objects.

The first question is what is the _exact_ error message you get. It
should provide fully-qualified names for the types involved in the
cast...what are those names? Chances are, at least one of them is not the
type you thought it would be. This is usually a namespace problem, where
one type came from a different namespace than the other and thus in fact
isn't related to the other.

But without knowing the exact, complete text of the error and without a
concise-but-complete code sample that reliably reproduces the problem,
it's hard to know for sure.

Pete
 
T

Trevor

Pete,

I was typing a long, reply message when I hovered over the signature of the
ClearFields(ControlCollection lst) function and discovered that the namespace
there was System.Windows.Forms.FORM.ControlCollection instead of
System.Windows.Forms.Control.ControlCollection.

Subtle, but you were correct. Thank you. No explicit cast needed, and my
faith in my understanding of overloading in c sharp is restored.

Trevor
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top