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
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.
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
}
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
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.