GetType() question

  • Thread starter Thread starter h
  • Start date Start date
H

h

Hi!

I have a user control called ListItemControl. This works ok:

ListItemControl li = new ListItemControl();

When I iterate with Enumerator through all controls using:

IEnumerator e = pnlList.Controls.GetEnumerator();
while (e.MoveNext())
{
object o = e.Current;
if(o.GetType().Equals(GetType(ListItemControl)))
{
i++;
}
}

I get 'ListItemControlTest.ListItemControl' denotes a 'class' where
a 'variable' was expected


What do I do wrong? I looked at the MSDN sample and it looked pretty
straight forward, but I can't get it to work.

thanks,
h
 
You should be using typeof() instead of GetType() or just use the is keyword.

if ( o is ListItemControl ) {
}
 
You use GetType() to get the type from an object instance. To get a type
from a classname, use typeof():
so, instead of:
if(o.GetType().Equals(GetType(ListItemControl)))
use
if(o.GetType().Equals(typeof(ListItemControl)))


// word of caution: I haven't tried to compile your code, but I think this
should solve that problem.

Oh, I'm curious: Why did you explicitly retrieve the enumerator instead of
just using a foreach() loop?
 
Oh, I'm curious: Why did you explicitly retrieve the enumerator instead of
just using a foreach() loop?

I'm still getting used to C# (late transition from VB which I have
used for quite a while). I was looking for "better" or other way to do
this.

Can you give advice if this is preferable way or not?

thanks everyone for your replies!

h
 
The only reason that I asked is that the enumerator is usually something
that you don't touch directly. Instead, if the object that you want to loop
through supports IEnumerable, you generally use a foreach loop (which uses
the enumerator under the covers for your). The foreach lets you declare a
variable for the member type of the collection you are enumerating. The form
looks like this:

foreach(MemberType memberVar in CollectionToBeEnumerated)
{
}

Basically, this uses the enumerator to loop through every member in the
collection. Each member is cast as MemberType and assigned to memberVar.

So, you could rewrite your code something like this (haven't tried
compiling, might need some tweaking):

foreach(Control aControl in pnlList.Controls)
{
if(aControl is ListItemControl)
i++;
}

NOTE: I am using Control because I know that all of the members of Controls
inherit from control. If I use a type that is too restrictive I will get
invalid cast errors. So, if I used TextBox, and there was a button in the
Controls collection, I would get an invalid cast exception when I hit the
button.
 
Back
Top