tags:

views:

815

answers:

4
+1  Q: 

ArrayList in C#

Can we pass ArrayLists as arguments to methods in C#?

+1  A: 

yes you can.

Zahir
+5  A: 

Sure, why not:

public void SomeMethod(ArrayList list)
{
    // your code here
}

But as Jon S. mentioned using interfaces is preferred instead of hard coded types.

public void SomeMethod(IList list)
{
    // your code here
}

See also:

Koistya Navin
+17  A: 

Absolutely. However, you rarely should. These days you should almost always use generic types, such as List<T>.

Additionally, when declaring the parameters of a method, it's worth using interfaces where you can. For instance, if you had a method like this:

public void SomeMethod(ArrayList list)

then anyone calling it is forced to use ArrayList. They can't use List<T> even if they want to. If, on the other hand, you declare your method as:

public void SomeMethod(IList list)

then they can use generics even if your code doesn't know about them.

Jon Skeet
I do not totally agree Jon, you should not use ArrayLists on public interfaces, though arrays may be used internally (private scope) for performance reasons.
Patrick Peters
Do you mean arrays or arraylists? I wouldn't specify ArrayList in an internal API for performance reasons without evidence that it was really significant... not that I'd use an ArrayList anyway when generics are available.
Jon Skeet
List<T>, and generics in general, may have problems serializing, if you consume a soap webservice the collections are always Arrays for this reason.
Bob The Janitor
@Bob: Yes, it makes sense to use arrays there - but then we're back to strongly typed collections as opposed to ArrayList. I've been specifically talking about ArrayList here as that's what the question asks about :)
Jon Skeet
A: 

Any Type can be passed as argument of method. Whether abstract one, or interface, or value type, or whatever.

Jon Skeet mention using of interfaces. Yes its good, but have small pitfall - you can not easily navigate from that method to its usage.

Aleksei