Arraylist: Is that right or is there a better way to do it?

Asked

Viewed 46 times

2

I know a bit of java, but now I’m venturing into C#, but a question came up here: In java we instantiated an Arraylist like this:

ArrayList<Tipo> nomeArray = new ArrayList<>();

We recover a value like this:

nomeArray.get(1).getNome();

And from my test here with C#, it seems like an instance:

ArrayList nomeArray = new ArrayList();//Não declara o tipo, estranho

And it seems to recover like this:

((Tipo) nomeArray[1]).Nome;//Toda vez que tenho que recuperar tenho que usar um TypeCast?

Is this the right way? Or is there a better way?

1 answer

2


In c# you must use the type List<tipo> which works basically like Arraylist in Java.

In c# Arraylist is marked as obsolete.

Arraylist was available before generics were implemented in . NET 2.0.

There is no advantage in Arraylist.Since generics are widely used by developers. I recommend using List<> or other type of collections or generic lists.

Example:

List<Tipo> variavel = new List<Tipo>();
variavel.add(variavelDoTipo);

var recuperaValor = variavel[0];

List uses the method add() to add an item to the collection (The type must be compatible with the list type).

To retrieve the value, you use the access syntax to a common array.

Example:

var variavel = nomeLista[0];

Browser other questions tagged

You are not signed in. Login or sign up in order to post.