How do I clear a generic collection using MethodInfo.Invoke?

I have a base class and a number of child classes that derive from this class that contain collections which need to be cleared when I call my base class' dispose method.  I am attempting to implement a method that will dynamically search my custom classes for fields that are collections, and then call the "Clear"method on these collections to reclaim the resources, before it is garbage collected.  I a doing this so I dont'have to write the same function 20 times for each of my child classes.

I am able to reflect to the method I need, however when i attempt to invoke the method I get a target exception error and don't understand why.  My code is below:

Public Sub ClearCollections()
        Dim xField As FieldInfo, xfields As FieldInfo()
        Dim xType As Type
        Dim xMethod As MethodInfo
        Dim xType2 As Type
        Dim args() As Object
        xType = MyClass.GetType
        'First get the fields
        xfields = xType.GetFields
        For Each xField In xfields
            If xField.FieldType.FullName.ToUpper.Contains("COLLECTION") Then
                xType2 = xField.FieldType
                'Clear the collection
                xMethod = xType2.GetMethod("Clear")
                args = xMethod.GetParameters
                xMethod.Invoke(xField, Nothing)
            End If
    End Sub

Open in new window

Who is Participating?
Jaime OlivaresConnect With a Mentor Software ArchitectCommented:
how is defined MyClass?
is it a class or an object. If it is a class, you need an object to invoke, if it is an object, it should be something like:

          If xField.FieldType.FullName.ToUpper.Contains("COLLECTION") Then
                Dim o as Object
                o = xField.GetValue(MyClass)  ' here is the instance of the field
                ' get the method based on instance type
                xMethod = o.GetType().GetMethod("Clear")
                xMethod.Invoke(o, Nothing)
Jaime OlivaresSoftware ArchitectCommented:
could you post the error message?
I forgot my crystal ball at home ;)
csjordanAuthor Commented:
Sure! Error message is "Object does not match target type."

Not sure if it matters but the collection is a system.collections.generic.dictionary.

csjordanAuthor Commented:
It is a class... so are you saying I need to create an instance of the class?  How would I do this dynamically?
csjordanAuthor Commented:
That code snip you sent did the trick.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.