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.
MyMethod(List<T> list)
is an invalid method signature (unless your class is a generic class with a Type ParameterT
) – Federico Berasategui Oct 2 '13 at 14:13MyClass1
andMyClass2
have some common base type or interface? Do they share a lot of common properties or methods? – Joel Coehoorn Oct 2 '13 at 14:22