Roshan
Roshan

Reputation: 717

ArrayList in C#

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

Upvotes: 2

Views: 4621

Answers (4)

Aleksei
Aleksei

Reputation: 418

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.

Upvotes: 0

Konstantin Tarkus
Konstantin Tarkus

Reputation: 38428

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:

Upvotes: 5

Jon Skeet
Jon Skeet

Reputation: 1504122

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.

Upvotes: 18

Zahir J
Zahir J

Reputation: 1179

yes you can.

Upvotes: 1

Related Questions