makoshichi
makoshichi

Reputation: 2390

Using List<T> in 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.

Upvotes: 35

Views: 112371

Answers (4)

Pradeep Yadav
Pradeep Yadav

Reputation: 93

Basically, In C#, List < T > class represents a strongly typed list of objects that can be accessed by index.

And it also supports storing values of a specific type without casting to or from object.

we can use in Interger value & String Value in the List.

Upvotes: 1

Chris Mantle
Chris Mantle

Reputation: 6683

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.

Upvotes: 18

Royi Mindel
Royi Mindel

Reputation: 1258

You need to let c# know what type is sent:

List<MyClass1> list1 = getListType1();
List<MyClass2> list2 = getListType2();

if (someCondition)
    MyMethod<MyClass1>(list1);
else
    MyMethod<MyClass2>(list2);

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

Upvotes: 7

Mathew Thompson
Mathew Thompson

Reputation: 56429

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

Upvotes: 53

Related Questions