I’m working with ArrayList in C# and I am wondering how I can add objects to an ArrayList and then retrieve the values from it?
In short, how can I add, delete, edit and read from an ArrayList containing objects of classes?
Thankful for all help!
Unless you are in a situation where you must use .NET 1.0/1.1, or need to interact with legacy code that uses
ArrayList– you should really avoid usingArrayListsin new code. Use the generic collection typeList<>instead.The operations to add, remove, and replace an item in
List<T>are quite straightforward.Let’s say you have some hypothetical type
Animal, instances of which you will store in a list:The public interfaces for
List<T>andArrayListare actually quite similar. The main difference, is that ArrayList can only storeobjectreferences since it was implemented before .NET supported generics.In the example above, you MUST cast types like
int(which are value types in .NET) to object. This results in a boxing conversion – which copies the int value type to a new location on the heap, and passes it to ArrayList. Boxing conversions, are one of the disadvantages of usingArrayList–List<T>avoids this by virtue of being a generic class. Another issue is thatArrayListdoes not prevent you from mixing different types in the list together. For instance:are both allowed. However, when accessing elements of an
ArrayList, you must know what type you are trying to retrieve. This makesArrayListmore fragile as a collection type, because the caller must write code to either protect themselves from arbitrary types being stored in theArrayList, or else use reflection and runtime type checks to convert the values being stored.List<T>avoids both of these problems by allowing the compiler to help verify that only appropriate types are stored in the collection (those that match the type parameterTinList<T>).There’s a great deal more that could be written about interacting with collections – and in fact there is. Here’s a link to just one of many great books on the subject. My advice would be, before you begin writing code in .NET/C#, you should take the time to familiarize yourself with the basic concepts of the C# language and type system – what are reference vs. value types. What are primitives. What are generics. etc. This will help ensure that when you start writing code, the code does what you need it to do. C# has a sophisticated and rich type system- as well as a vast library of framework classes. It’s important to have a good grounding in the core aspects of the language before you get too deep into writing actual code. Examples like those I show above will only get you so far – and they already introduce numerous language concepts: variables, constructors, generics, boxing conversions, etc.