C#C
C#2y ago
5 replies
jborean

Invoke method with [Optional] with default value through Reflection

Is it possible to through reflection to invoke a method with an
[Optional]
attribute. For example
Type.Missing
works for an argument with a default value but not for an
[Optional]
argument.
using System;
using System.Reflection;
using System.Runtime.InteropServices;

public class Program
{
    public static void Main(string[] args)
    {
        object? test1 = typeof(Program).GetMethod("MethodWithDefault").Invoke(null, new[] { Type.Missing });
        object? test2 = typeof(Program).GetMethod("MethodWithOptional").Invoke(null, new[] { Type.Missing });
        Console.WriteLine(test1);
        Console.WriteLine(test2);
    }
    
    public static int MethodWithDefault(int value = 1) => value;
    public static int MethodWithOptional([Optional]int value) => value;
}
Was this page helpful?