1

I dont' now how can I get a instance of a parameter for Invoke (please see the sample variable "listInstance"). I don't want to create a new list (with Activator.CreateInstance), I want to add an object to the existing list instance. How can I get the object Sample.Samples?

using System.Collections.Generic;

public class Class<T>
{
  public readonly IList<T> InternalList = new List<T>();
  public virtual void Add(T obj)
  {
    InternalList.Add(obj);
  }
}
public class Sample
{
  public Class<Sample> Samples { get; set; } = new Class<Sample>();
}

class Program
{
  static void Main(string[] args)
  {
    var cla = new Sample();
    var propertyInfo = cla.GetType().GetProperty("Samples");
    var newSample = new Sample();
    var addMethod = propertyInfo.PropertyType.GetMethod("Add");

    var listInstance = ???; // Instance of the Property Sample.Samples

    addMethod.Invoke(listInstance, new[] { newSample });
  }
}
hoss
  • 25
  • 3

3 Answers3

0

Get the value of the property and invoke the ´Add´ method on it:

class Program
{
    static void Main(string[] args)
    {
        var cla = new Sample();
        var propertyInfo = cla.GetType().GetProperty("Samples");
        var addMethod = propertyInfo.PropertyType.GetMethod("Add");
        var samples = propertyInfo.GetValue(cla); // retrieve property value
        var newSample = new Sample();

        addMethod.Invoke(samples, new[] { newSample });
    }
}
Alessandro D'Andria
  • 8,663
  • 2
  • 36
  • 32
0
var listInstance = (Class<Sample>)propertyInfo.GetValue(clr)

You can cast it directly to the expected type, so you don't need to invoke a method using reflection.

0

I think this should works:

PropertyInfo propInfo = newSample.GetType().GetProperty("Samples"); //this returns null
var samples = propInfo.GetValue(newSample, null);
Mohsen Esmailpour
  • 11,224
  • 3
  • 45
  • 66