The type argument for a generic type parameter can only be inferred if it is used in an input parameter. In all other cases, the type parameter must be declared explicitly.
The type parameter can be inferred for all of these:
public static T Foo<T>(T bar) { ... }
int x = Foo(42);
public static T FirstOrDefault<T>(IEnumerable<T> source) { ... }
string item = FirstOrDefault(myListOfStrings);
public static IEnumerable<T> Where<T>(IEnumerable<T> source, Func<T, bool> predicate) { ... }
IEnumerable<Bar> filteredList = Where(myListOfBars, bar => someCondition);
But when none of the input parameters are related to the type parameter, you have to specify the type parameter explicitly:
public static List<T> MakeAList<T>(int x, string y) { ... }
List<Bar> myList = MakeAList(42, "Hello");
List<Bar> myList = MakeAList<Bar>(42, "Hello");
So, in your example, you need:
lstTransferObject = GetDtoList<TransferObject>(a, b);
HOWEVER, this
will not work. Your code will compile, but you will get an exception at runtime, because you're trying to add an object of one type to a list of a different type. If you replace the
dynamic
keywork with either
object
or
T
, you'll get a compiler error which shows you what the problem is.
If you want to return a list of
dynamic
objects, then your method should return
List<dynamic>
. If you want to return a list of a specific type, then you need to create an instance of that specific type in your loop.