Search code examples
c#datetimeinvokecreateinstance

C# Cannot convert from 'System.DateTime' to 'object[]' methodinfo.invoke


Look I maybe approaching this the wrong way and direction is more than welcome.

I'm trying to trigger all the Start methods in my solution.

The Start method takes a datetime

However when trying to pass the date as a parameter of "Invoke" I run into the error

cannot convert from System.DateTime to object[]

Any thoughts welcome

Thanks gws

scheduleDate = new DateTime(2010, 03, 11);

Type[] typelist = GetTypesInNamespace(Assembly.GetExecutingAssembly(), "AssetConsultants");

foreach (Type t in typelist)
{
    var methodInfo = t.GetMethod("Start", new Type[] {typeof(DateTime)} );
    if (methodInfo == null) // the method doesn't exist
    {
       // throw some exception
    }

    var o = Activator.CreateInstance(t);                 
    methodInfo.Invoke(o, scheduleDate);
}

Solution

  • The second parameter of method Invoke expects an object array with your parameters. So instead of passing a DateTime wrap it in object arrray:

    methodInfo.Invoke(o, new object[] { scheduleDate });