Question

I thought that there was some way in .net 3.0 to give an array list a type so that it didnt just return Object's but I'm having trouble doing so. Is it possible? If so, how?

Was it helpful?

Solution

List<T> was introduced with generics in .NET 2.0:

using System.Collections.Generic;

var list = new List<int>();
list.Add(1);
list.Add("string"); //compile-time error!
int i = list[0];

OTHER TIPS

You're probably looking for List<T>, available since .NET 2.0, or for any other of the generic types available from System.Collections.Generic or System.Collections.ComponentModel.

If you have to use ArrayList and can't start using List, and you know the type of every element in that ArrayList you can do:

  string[] stringArray = myArrayList.ToArray(typeof(string)) as string[];

If something in myArrayList wasn't a string, in this case, you would get an InvalidCastException.

If you can, I would start using List as OregonGhost mentioned.

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