Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using List<T> in C# (Generics)

Tags:

c#

generics

That's a pretty elementary question, but I have never delved into generics before and I found myself in the need to use it. Unfortunately I don't have the time right now to go through any tutorials and the answers I found to related questions so far aren't what one could call basic, so there we go:

Let's say I have the following:

List<MyClass1> list1 = getListType1(); List<MyClass2> list2 = getListType2();  if (someCondition)     MyMethod(list1); else     MyMethod(list2); 

And of course

void MyMethod(List<T> list){     //Do stuff } 

Well, I thought it would be this simple, but apparently it is not. VS warns me that

The type arguments for method MyMethod(System.Collections.Generic.List) cannot be inferred from the usage

and if I compile it anyway, I get a

The type or namespace name 'T' could not be found

error.

In the many answers I found, I read that I have to declare what T is, which makes sense, but I couldn't quite grasp how to do so in such a simplistic scenario. Of course, those answers created even more questions in my mind, but right now I just want an explanation of what I'm doing wrong (besides not studying generics) and how to make it right.

like image 241
makoshichi Avatar asked Oct 02 '13 14:10

makoshichi


People also ask

How do I return a string from a list in C#?

In C# you can simply return List<string> , but you may want to return IEnumerable<string> instead as it allows for lazy evaluation. @Marc: Certainly, but if you return List<string> you don't have the option even with a lazy source.

How does list work in C#?

Lists in C# are very similar to lists in Java. A list is an object which holds variables in a specific order. The type of variable that the list can store is defined using the generic syntax. Here is an example of defining a list called numbers which holds integers.


2 Answers

You need to declare T against the method, then C# can identify the type the method is receiving. Try this:

void MyMethod<T>(List<T> list){     //Do stuff } 

Then call it by doing:

if (someCondition)     MyMethod(list1); else     MyMethod(list2); 

You can make it even stricter, if all classes you are going to pass to the method share a common base class:

void MyMethod<T>(List<T> list) where T : MyClassBase 
like image 194
mattytommo Avatar answered Oct 10 '22 09:10

mattytommo


You need to add the generic type parameter for T to your method:

void MyMethod<T>(List<T> list) { 

The compiler doesn't know what T represents, otherwise.

like image 27
Chris Mantle Avatar answered Oct 10 '22 09:10

Chris Mantle