Search code examples
c#listreflectionmethodinfo

Reflection Methodinfo - how to use remove for a reflected property (List)


My goal is to remove entries from unknown list / collection at compile time.

I'm passing an interface as parameter. With reflection I receive the associated collection and method "Remove".

private void DeleteRowOfUnknownCollection(IMakeClassUsableForStandardGridButton uiModel) {
        Type typView = this.GetType();
        PropertyInfo propInfoCollection = typView.GetProperty(GetCollectionPropertyNameByModel(uiModel));
        object instanceOfCollection = propInfoCollection.GetValue(this);
        Type propTyp = instanceOfCollection.GetType();
        MethodInfo methodRemoveOfCollection = propTyp.GetMethod("Remove");

        object ToBeRemovedUiModel = Activator.CreateInstance(uiModel.GetType());

        methodRemoveOfCollection.Invoke(instanceOfCollection, new [] { ToBeRemovedUiModel } );
    }

Plain and simple - I don't know how to use the Remove method when its reflected and expecting an object intantiated with new.

Any ideas how to remove the passed uiModel?

Thanks in advance!


Solution

  • Thanks to Lasse who pointed to a mistake in code. Passing a new instance of a class instead of the parameter uiModel object.

    methodRemoveOfCollection.Invoke(instanceOfCollection, new [] { uiModel } );
    

    Now it works properly!