How to call Method with optional parameters using reflections c#

Viewed 161

I'm calling a methods using reflections. However due to some requirement one of the method parameters are changed and keeping new parameters as optional parameters. here is code

Void Method1(string request, string constants, string count = null)

Void Method2(string request, string constants)

In Method1 count parameter is optional.For the above methods, I'm calling using reflections Here is the code :

result = methodInfo.Invoke(classInstance, new object[] {request, constants});

I have tried with below approach but getting exception

result = methodInfo.Invoke(classInstance, new object[] {request, constants ,System.Type.Missing});

Got below exception for Method2 the above code is working for Method1

Parameter count mismatch.

Please suggest me for optional parameters in method using reflections

Thanks in Advance!

1 Answers

Optional parameters: aren't actually optional - all that happens is that the compiler normally supplies the omitted value automatically for you. Since you're not using a compiler here, you'll need to supply it yourself, using new object[] {request, constants, null}. Note that if you want to properly respect the default value (rather than knowing it is null in this case), you'd need to look at the ParameterInfo, specifically .HasDefaultValue and .DefaultValue.

Example (not using ParameterInfo, note):

using System;
using System.Reflection;

class P
{
    static void Main()
    {
        string request = "r", constants = "c", count = "#";
        var classInstance = new P();

        typeof(P).GetMethod(nameof(Method1),
            BindingFlags.Instance | BindingFlags.NonPublic)
            .Invoke(classInstance, new object[] { request, constants, null });

        typeof(P).GetMethod(nameof(Method1),
            BindingFlags.Instance | BindingFlags.NonPublic)
            .Invoke(classInstance, new object[] { request, constants, count });

        typeof(P).GetMethod(nameof(Method2),
            BindingFlags.Instance | BindingFlags.NonPublic)
            .Invoke(classInstance, new object[] { request, constants });
    }

    void Method1(string request, string constants, string count = null)
        => Console.WriteLine($"#1: {request}, {constants}, {count}");

    void Method2(string request, string constants)
        => Console.WriteLine($"#2: {request}, {constants}");
}
Related