Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic List<T> as parameter on method

How can I use a List<T> as a parameter on a method, I try this syntax :

void Export(List<T> data, params string[] parameters){  } 

I got compilation error:

The type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference?)

like image 219
Jonathan Escobedo Avatar asked Oct 27 '09 21:10

Jonathan Escobedo


People also ask

How do you determine what type a generic parameter T is?

Use the IsGenericType property to determine whether the type is generic, and use the IsGenericTypeDefinition property to determine whether the type is a generic type definition. Get an array that contains the generic type arguments, using the GetGenericArguments method.

How can generic type pass lists?

To take a generic List<T> vs a bound List<int> you need to make the method generic as well. This is done by adding a generic parameter to the method much in the way you add it to a type. void Export<T>(List<T> data, params string[] parameters) { ... }

What does the T designator indicate in a generic class?

Its instances (only one per type exists) are used to represent classes and interfaces, therefore the T in Class<T> refers to the type of the class or interface that the current instance of Class represents.

What is T on parameter C#?

In C#, the “T” parameter is often used to define functions that take any kind of type. They're used to write generic classes and methods that can work with any kind of data, while still maintaining strict type safety.


2 Answers

To take a generic List<T> vs a bound List<int> you need to make the method generic as well. This is done by adding a generic parameter to the method much in the way you add it to a type.

Try the following

void Export<T>(List<T> data, params string[] parameters) {  ... } 
like image 93
JaredPar Avatar answered Sep 22 '22 06:09

JaredPar


You need to make the method generic as well:

void Export<T>(List<T> data, params string[] parameters){  } 
like image 37
Fredrik Mörk Avatar answered Sep 24 '22 06:09

Fredrik Mörk