❔ Difference between these variants
I'm learning c# right now and I saw something as
ArrayList myList = new ArrayList();
IList myList = new ArrayList();
ICollection myList = new ArrayList();
so in this case defining myList as in the first one -which is "ArrayList myList = new ArrayList();"- it has more methods in it. But we can do the others as well. My question is if you're able to have more methods and do much more things, why use IList myList = new ArrayList(); or ICollection myList = new ArrayList(); instead ? What is the difference ?
7 Replies
Do not use ArrayList
why though ? I started learning couple days ago so I don't know
It's old and completely outdated. The official documentation for it even states to never ever use it.
You should always use
List<T>
if you need a list which can grow and shrink.Yeah I was in generic list lesson right now actually but before it he explains ArrayLists first but I just wondered about that variants
sure
In this situation, they aren't very useful. What they do is just define some common behavior, eg. "all kinds of lists" and "all kinds of collections". This is primarily useful if you're writing a method (you'll learn about those later) which takes something as a parameter and expects that thing to be able to act as a list or collection. While you could make the method take a
List<T>
as its argument, this forces everyone who wants to use the method to supply specifically a List<T>
, but if you use ICollection<T>
, then you could pass the method a Stack<T>
, an array, or any other kind of collection.I see
thank you so much
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.