Downcasting objects in an ArrayList

  • Thread starter Thread starter Fernando Rodríguez
  • Start date Start date
F

Fernando Rodríguez

Hi,

I have a class called UrlFetcher and keep several instances inside an
ArrayList. This class has a fecth() method.

When I iterate through the list calling the fetch() method, I have to downcast
from object to UrlFetch. This is pretty ugly...

--------------------------------------------------------------
IEnumerator fetcher = fetchers.GetEnumerator();
UrlFetcher f;
while( fetcher.MoveNext() )
{
f = (UrlFetcher)fetcher.Current;
f.fetch();
}
 
No.

The Current property returns an Object - that is the definition of
IEnumerator. You have to then cast it to the appropriate type.

Why is it ugly? It is just placing some paren with the type name in front of
the call to Current. What is the big deal?

And how else would you propose this could work? How could the compiler know
that the 'fetcher' variable of type IEnumerator is in fact enumerator over
an array list that happens to have UrlFetcher objects in it?
 
Fernando Rodríguez said:
I have a class called UrlFetcher and keep several instances inside an
ArrayList. This class has a fecth() method.

When I iterate through the list calling the fetch() method, I have to downcast
from object to UrlFetch. This is pretty ugly...

--------------------------------------------------------------
IEnumerator fetcher = fetchers.GetEnumerator();
UrlFetcher f;
while( fetcher.MoveNext() )
{
f = (UrlFetcher)fetcher.Current;
f.fetch();
}

Well, the cast has to be there, but C# has syntax to make it a lot
easier:

foreach (UrlFetcher f in fetchers)
{
f.fetch();
}
 
You should make use of the "foreach" statement:

foreach (object f in fetcher) {
(UrlFetcher)f.fetch();
}

and to avoid the casting.

foreach (UrlFetcher f in (UrlFetcher []) fetcher.ToArray( typeof(
UrlFetcher ) ) {
f.fetch();
}


Michael
 
No.

The Current property returns an Object - that is the definition of
IEnumerator. You have to then cast it to the appropriate type.

Why is it ugly? It is just placing some paren with the type name in front of
the call to Current. What is the big deal?

And how else would you propose this could work?

As in C++, for instance, where you can create a std::list<UrlFetcher> on the
fly...
 
Well, this isn't C++. Given the structure of .NET, there is no way to do
this any other way. And like I said, I don't see anything ugly about it -
it's just a cast, not 50 extra lines of code.

2.0 does have generics though.
 
Michael Thomas (Microsoft) said:
You should make use of the "foreach" statement:

foreach (object f in fetcher) {
(UrlFetcher)f.fetch();
}

and to avoid the casting.

foreach (UrlFetcher f in (UrlFetcher []) fetcher.ToArray( typeof(
UrlFetcher ) ) {
f.fetch();
}

You don't need to create a new array to do that. Just let foreach do
the casting:

foreach (UrlFetcher f in fetchers)
{
f.fetch();
}
 
Back
Top