Question

ArrayList, which I use in legacy Compact Framework code, does not seem to be available in newfangled (.NET 4.5.1) code.

I am storing instances of custom classes in it.

What is a good replacement for it - List<Object>, or is there something more suitable?

Was it helpful?

Solution

As @HighCore mentioned in his comment, you should use the generic form of List, List<T>. If you have several classes defined that you need to include in that List, they probably have common properties, methods. In that case, you can make an abstract class for the group of classes.

List<Object> is a possible replacement, but not a good one.

OTHER TIPS

Yes, List<object> is a good replacement for ArrayList.

If you want to have a list type that can store anything, you can use either ArrayList or List<object> as the collection type. It will have the same performance and behavior characteristics.

The question is this: Why are you using ArrayList to begin with? If you're coming from a pre-generics version of .NET, then you probably have no choice. You either have strongly typed arrays (which are constant in size) or you have ArrayList which is dynamic in size but overly "generic" in type. It can store anything.

Now, with the new .NET and C# versions, it's time to let all that go.

(regarding comments about "net .NET and C# version": obviously "new" here is not new as in 2014-new, but compared to whatever textbook or sourcecode the OP has learned from generics is "new" compared to using ArrayList.)

You want your collections to be strongly typed. It makes your life easier since you know what fields/properties/members are available on the items of the collection etc.

As such, what you want to do is to figure out what the base type of your elements are, and make the collection a List<BaseType> or similar, this will make your life a whole lot easier.

If you're storing a bunch of integers, use List<int>. If you're storing a bunch of strings, use List<string>. If you're storing a bunch of objects of type SomeCustomObject, use List<SomeCustomObject.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top