© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•3y ago•
21 replies
Kaihyo

❔ Building a delegate with a Type and a MethodInfo keeps throwing ArgumentException

Hi ! I'm trying to build a delegate from a Type and a MethodInfo. The type correspond to the method 1st argument's type. I have the following code :
public System.Delegate CreateRemoveMethod(System.Type elementType, System.Reflection.MethodInfo methodInfo)
        {
            if (methodInfo == null)
            {
                return null;
            }

            System.Reflection.ParameterInfo[] parameters = methodInfo.GetParameters();
            if (parameters.Length != 1 && parameters[0].ParameterType != elementType)
            {
                return null;
            }

            var action = typeof(System.Action<>).MakeGenericType(elementType);
            return methodInfo.CreateDelegate(action);
        }
public System.Delegate CreateRemoveMethod(System.Type elementType, System.Reflection.MethodInfo methodInfo)
        {
            if (methodInfo == null)
            {
                return null;
            }

            System.Reflection.ParameterInfo[] parameters = methodInfo.GetParameters();
            if (parameters.Length != 1 && parameters[0].ParameterType != elementType)
            {
                return null;
            }

            var action = typeof(System.Action<>).MakeGenericType(elementType);
            return methodInfo.CreateDelegate(action);
        }

Unfortunately, the function throws an exception every time I call it, saying method arguments are incompatible.
The signature of the method I'm using to test it is the following one :
void LogInConsole(BaseClass item)
void LogInConsole(BaseClass item)
.
I'm calling CreateRemoveMethod like this :
CreateRemoveMethod(typeof(BaseClass), methodInfo)
CreateRemoveMethod(typeof(BaseClass), methodInfo)
, with methodInfo corresponding LogInConsole that I gathered through reflection.
Would you have any insight on what I'm doing wrong here ? 🙂
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

Create a `Delegate` from a `MethodInfo` [Answered]
C#CC# / help
4y ago
Generically creating a delegate from a MethodInfo with parameter upcasting
C#CC# / help
17mo ago
Delegate.CreateDelegate returns "ArgumentException: method arguments are incompatible"
C#CC# / help
2y ago
Delegate type mismatch
C#CC# / help
3y ago