Specifying ArrayList Item Type

I thought that in .net 3.0 there is some way to give a list of an array of type so that it just does not return an object, but I am having problems with this. Is it possible? If so, how?

+4
source share
3 answers
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]; 
+14
source

You are probably looking for a List <T> , available with .NET 2.0, or for any other of the common types available from System.Collections.Generic or System.Collections.ComponentModel.

+3
source

If you need to use an ArrayList and cannot start using List, and you know the type of each element in this ArrayList, which you can do:

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

If something in myArrayList was not a string, then you will get an InvalidCastException.

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

-1
source

Source: https://habr.com/ru/post/1277256/


All Articles