Anton
Anton

Reputation: 910

Can I use List<object> as a formal parameter in a method?

I'm trying to abstract out a method so I can use it for all my List objects.

Currently my method declaration looks like:

private void GetResults(List<myclass1> testList, List<myclass1> masterList, string tableName)

What I'd like to do is generalize the formal parameters to:

private void GetResults(List<object> testList, List<object> masterList, string tableName)

Then I'd like to just pass in whichever type of list I need. This of course is giving me a compile error (for the generalized attempt).

I'm calling the method like:

List<myclass1> testList = new List<myclass1>();
List<myclass1> masterList = new List<myclass1>();
GetResults(testList, masterList, "form_table");

Is there a way to do this?

Upvotes: 2

Views: 212

Answers (1)

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

You can use Generics

private void GetResults<T>(List<T> testList, List<T> masterList, string tableName)

The type of T will be inferred from usage based on your parameters type.

This assumes both parameters will be the same type.If they won't, you need another generic argument for the second parameter.

Upvotes: 9

Related Questions