Problem ArrayList - C #

1

I have the problem of wanting to extract an element from an ArrayList as such, because when I have to use that element for some operation, it tells me that it is of type object, here is the example

    ArrayList Lista = new ArrayList() { 1, 3, 4, "100" };
    Console.WriteLine(Lista[1]+2);

In this case the output would be 5 , but as explained before the problem is that it tells me that it is object type and that the operation can not be carried out.

    
asked by Shiki 26.01.2018 в 04:31
source

3 answers

2

If you are forced to use ArrayList because the elements can be of any type, you will have to cast / convert the elements before using them. For example:

ArrayList Lista = new ArrayList() { 1, 3, 4, "100" };
foreach(var l in Lista) {
    if (l is int)
        Console.WriteLine(((int) l) + 2);
    if (l is string)
        Console.WriteLine(int.Parse(l) + 2);
    // etc para los distintos tipos de datos
}
    
answered by 26.01.2018 / 05:34
source
0

ArrayList stores the data as object type so you need to cast the corresponding data type to perform the operation in this case int:

Console.WriteLine(Convert.ToInt32(Lista[1]) + 2);

or alternatively

Console.WriteLine((int)(Lista[1]) + 2);
    
answered by 26.01.2018 в 04:44
0

ArrayList stores data type Object if you want to avoid caster usa generics example

List<int> list1 = new List<int>();

This way you avoid the casting and if you get to put a different data type you will get the error in compile time, besides being a value with a declared data type what you are saving in the generic list is much faster than saving an object type

    
answered by 26.01.2018 в 05:35