Nilesh Barai
Nilesh Barai

Reputation: 1322

Error in type conversion using reflection method invoke

I have a method call as follows:

splitByRegex(regexPattern, lines, ref lineIndex, capacity, result =>
{
      List<object> res = result.Select(selector).ToList();
      MessageBox.Show(res[0].GetType().ToString());
      collection.GetType().GetMethod("AddRange").Invoke(collection, new object[] { res });
});

splitByRegex method will split the data and will give back result.

I have to add the obtained result to the generic collection.

Type of selector function: Func<Tuple<string, string, string>, object>

Sample selector Function: x => new Merchant { MerchantName = x.Item1, Count = Convert.ToInt64(x.Item2), Percentage = Convert.ToDecimal(x.Item3) }

While executing AddRange method call using reflection: collection.GetType().GetMethod("AddRange").Invoke(collection, new object[] { res });

I am getting following error:

Object of type 'System.Linq.Enumerable+WhereSelectListIterator2[System.Tuple3[System.String,System.String,System.String],System.Object]' cannot be converted to type 'System.Collections.Generic.IEnumerable`1[Processing.Merchant]'.

When I try to print the type of any one object from the List<object> res MessageBox.Show(res[0].GetType().ToString());, it shows it as Merchant type object. So why am I getting this error?

Upvotes: 2

Views: 232

Answers (1)

Nilesh Barai
Nilesh Barai

Reputation: 1322

@John - Thanks for pointing me to Eric's post. This makes it clear. I fixed it by not calling AddRange method, however call Add method of the generic collection for each element in the obtained result.

splitByRegex(regexPattern, lines, ref lineIndex, capacity, result =>
{
     MethodInfo method = collection.GetType().GetMethod("Add");
     result.Select(selector).ToList().ForEach(item => method.Invoke(collection, new object[] { item }));
});

Upvotes: 2

Related Questions