Search code examples
c#.netparametersdelegatesdynamic-invoke

How do I pass an object array into a method as individual parameters?


I have the following code:

public class MyClass
{
    private Delegate m_action;
    public object[] m_args;

    public MyClass()
    {

    }

    public MyClass(Delegate action, params object[] args)
    {
        m_args = args;
        m_action = action;
    }

    public void Execute()
    {
        m_action.DynamicInvoke(m_args);
    }
}

The problem with this approach is that the m_args is an object itself, and its contents are not being flattened out into individual params entries. How can I fix this?


Solution

  • I think you are mistaken. The params seems to work as intended. Here's a simpler example showing that it works:

    static void f(params object[] x)
    {
        Console.WriteLine(x.Length);
    }
    
    public static void Main()
    {
        object[] x = { 1, 2 };
        f(x);
    }
    

    Result:

    2
    

    See it working online: ideone