Wheels
Wheels

Reputation: 155

C# Reflection - Add element to collection

I have a method that tries to find a Hash<> type collection that exists in an object and add a new element to that collection. Right now I have the following snippet:

/// <summary>
    /// Adds an element to a list
    /// </summary>
    /// <param name="target">The object that contains the collection of the type we are searching for.</param>
    /// <param name="toAdd">the object to add to the collection.</param>
    /// <param name="propertyType">The type of the object we want to add to the collection.</param>
    public void AddValueCollection(object target, object toAdd, Type propertyType)
    {
        PropertyInfo propertyInfo = target.GetType().GetProperties().FirstOrDefault(o => o.PropertyType.GenericTypeArguments.Length > 0 
            && o.PropertyType.GenericTypeArguments[0] == propertyType);

        if (propertyInfo != null)
        {
            object cln = propertyInfo.GetValue(????);
            propertyInfo.PropertyType.GetMethod("Add").Invoke(cln, new object[] { toAdd });
        }
    }

The problem I'm having is trying to get the collection out of the target so I can invoke the "Add" method and add the element.

Any ideia on how to do this?

ty all ^^

Upvotes: 0

Views: 822

Answers (1)

Richard Friend
Richard Friend

Reputation: 16018

You want to get the current value from the target, if so then.

 object cln = propertyInfo.GetValue(target);

Upvotes: 1

Related Questions