C# Reflection Lists: Object does not match target type
c#, reflection
Solution
You're trying to call `List.Add(Processor)` on `PC` - you want to call it on the value of the field:
field.FieldType.GetMethod("Add").Invoke(field.GetValue(fetched),
new[] {classContainer});
However, I'd personally advise you not to have public fields like this. Consider using properties instead.
Problem
Trying to add a class object into a List using reflection, but when invoking the Add method with my class object as a parameter, I get 'Object does not match target type' Here's the snippet code in concern (you can assume `classString = "Processor"` for now) ``` PC fetched = new PC(); // Get the appropriate computer field to write to FieldInfo field = fetched.GetType().GetField(classString); // Prepare a container by making a new instance of the reffered class // "CoreView" is the namespace of the program. object classContainer = Activator.CreateInstance(Type.GetType("CoreView." + classString)); /* classContainer population code */ // This is where I get the error. I know that classContainer is definitely // the correct type for the list it's being added to at this point. field.FieldType.GetMethod("Add").Invoke(fetched, new[] {classContainer}); ``` Then this is part of the class the above code is adding classContainers to: ``` public class PC { public List<Processor> Processor = new List<Processor>(); public List<Motherboard> Motherboard = new List<Motherboard>(); // Etc... } ```