I'm trying to attach a Generic list to a instance of a class using reflection, unlike when attaching simple objects method the PropertyInfo.SetValue(obj, value, index) is returning the exception {"Parameter count mismatch."} when value is an instance of List<SomeType> (as opposed to a string, int, bool or even a custom class).
That summery might not make much sense; The following may help to explain what I'm trying to do.
Say we are trying to populate the following class with reflection:
public class Foo
{
public virtual int someInt {get; set;}
public virtual IList<SomeClass> list {get; set;}
}
The method may look something like this:
public static T Parse<T>(HttpRequest request) where T : new()
{
returnObj = new T();
PropertyInfo[] properties = typeof(T).GetProperties();
foreach (PropertyInfo p in properties)
{
// Get a meaningful property name
string ins = System.Text.RegularExpressions.Regex.Replace(p.PropertyType.FullName, "([^,]*),.*$", "$1");
switch(ins)
{
// populate int
case "System.Int32":
p.SetValue(returnObj, Int32.Parse(request[p.Name]) , null);
break;
// populate list
case "System.Collections.Generic.IList`1[[SomeNamespace.Domain.SomeClass":
IList<SomeClass> list = new List<SomeClass>();
foreach (string s in request[p.Name].Split(','))
{
list.Add(new SomeClass(s));
}
// This will throw the exception 'Parameter count mismatch.'
p.SetValue(returnObj, list, null);
break;
}
}
return returnObj;
}
However when trying to add an instance of List (IList) in this way an exception is thrown.
Edit: To clarify, If been over this method with a fine tooth comb(Breakpoints) (well, the one in the application, not exactly this one) and all the variables are populated as expected; until SetValue throws an exception; if anyone needs some more information, do ask.
Edit2: So I built a smaller application to test this (In order to upload it as an example); and I'm having trouble recreating my own issue; As many of you have suggested this works. I'll update this question with the issue when I manage to track it down. Its probably something trivial, as these things so often are (The original codebase is massive and therefore not appropriate for me to post). Thanks for all your help so far and my apologies for wasting your time.
p.PropertyType.FullNamebefore you run theRegex?