24

I am a Java programmer, I have used a Java ArrayList before and now I want to have something like that in C#. Some of options I need are in this Java code:

String[] strs = new String[]{"str1" , "str2" , "str3" , "str4"};
ArrayList arrayList = new ArrayList(35);
arrayList.add(strs[0]);
arrayList.add(strs[1]);
arrayList.remove(0);
arrayList.set(0, strs[2]);
String s = (String) arrayList.get(1);

I used C# ArrayList and LinkedList, but they don't have these simple options that I need. Is there another option in C# supporting accessing objects with indexes, inserting and removing from certain index?

Rob
  • 26,989
  • 16
  • 82
  • 98
sajad
  • 2,094
  • 11
  • 32
  • 52
  • 2
    Use `List`,`List[index]` and [`List.RemoveAt`](http://msdn.microsoft.com/en-us/library/5cw9x18z(v=vs.80).aspx). – Tim Schmelter Sep 09 '12 at 20:23
  • wow that's confusing; nowadays it is common to think of a List as a shorthand for a Linked List, rather than a contiguous colection. – Dmytro Apr 16 '18 at 18:46

2 Answers2

31

use List <T>

 String[] strs = new String[]{"str1" , "str2" , "str3" , "str4"};
 List<string> stringList = new List<string>();
 stringList.add(strs[0]);
 stringList.add(strs[1]);
 stringList.RemoveAt(indexYouWantToDelete)     
 String s = stringList[0];

ArrayLists in c# come from the pre-generic era tho. Since C# 2.0 we have generic collections, List <T> being one example of that. As the comment on this answer says, if you use an ArrayList, the elements that you put into the arraylist will have to be boxed (to Object, because thats the only thing an ArrayList takes as input). If you want to access them after that, they will have to be explicitly unboxed, like what you did in your question. ( --> String s = (String) arrayList.get(1); )

using generic collections (like List <T>), there is no boxing anymore, as the compiler knows what datatype the list will consist of. In this case, Strings. You could also have a List<int>, List<char>, or List<whatever>, and you can use the same indexing functionality on them.

Thousand
  • 6,562
  • 3
  • 38
  • 46
  • 2
    it might be worth pointing out that the use of `ArrayList` is *not* recommended as it is non-generic and causes boxing. – Adam Sep 09 '12 at 20:27
  • thank you! firstly I thought that LinkedList is more advanced than pure List and I didn't note to that. – sajad Sep 09 '12 at 20:32
  • OK... I understood the generic data types are inherited from C and are equivalent to templates in C and C++. But non-generic data types are behaved like objects and need type casting. Thank you! – sajad Sep 09 '12 at 20:56
  • 2
    Here are the differences between C# and java generics and C templates: http://stackoverflow.com/a/31929/284240. – Tim Schmelter Sep 09 '12 at 22:13
3

Use List<T> ...........................................

which has Add Remove, RemoveAt indexers like list[i] etc.

L.B
  • 114,136
  • 19
  • 178
  • 224