Question

I tend to use ArrayLists of structures. It is then very easy to cycle through the list with a foreach.

The problem I have is I cant use a foreach to modify the structures contents and have to use a for and messy typecasts.

((dataStructure)files[x]).name = here;

Is there a tidier way to do it?

Was it helpful?

Solution

I know this sounds simplistic but just say no to mutable value types.

They're almost never the right solution to the problem. There are a very few exceptions, but classes are almost always the way to go.

In addition, if you're really using an ArrayList then you'll be incurring an unboxing cost already... (As Konrad says, if you can use .NET 2.0 then use generics.)

If you really insist on using mutable structures, then use a for loop instead of foreach. But please, please change to classes anyway.

OTHER TIPS

Yes, there is: don't use an untyped ArrayList, these types are deprecated in favour of the generic types in System.Collections.Generic. In your case: List<T>.

You still can't use it in conjunction with a foreach loop to modify structure values but at least you don't have to cast.

Use the generic version of ArrayList: List<DataStructure>.

This way things look a lot better:

files[x].name = here;

Yes, there are cases where List <T> also is not useful. In those cases the oldest trick in the manual works. Instead of foreach, you should use while loop:

while (listItem.Count >0)
{
//do operation with 0th element of List Item always like
 deletefunc(lisItem[0]);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top