-4

Im trying "Func" delegation.

    Func<int, string[], bool>(myFunc); //works OK
    Func<string[], bool>(myFunc); //Exception ???

Unhandled Exception: System.ArgumentException: Object of 'System.String'cannot be converted to type 'System.String[]'. Looks like "Func" doesn't like argument type "string[]" ?!?"

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, Delegate> commandHash = new Dictionary<string, Delegate>();
            commandHash.Add("Test", new Func<string[], bool>(Test));
            string[] str = { "justtext" };

            try
            {

                commandHash["Test"].DynamicInvoke(str);
            }
            catch
            {
                Console.WriteLine("Exception");
            }

        }
        static  bool Test(string[] s)
        {
            Console.WriteLine("Test");

            return true;
        }
    }
}


// CODE which works OK, what Im missing ?!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, Delegate> commandHash = new Dictionary<string, Delegate>();
            commandHash.Add("Test", new Func<string[], int, bool>(Test));
            string[] str = { "justtext" };

            try
            {

                commandHash["Test"].DynamicInvoke(str, 1);
            }
            catch
            {
                Console.WriteLine("Exception");
            }

        }
        static  bool Test(string[] s, int i)
        {
            Console.WriteLine("Test");

            return true;
        }
    }
}
kestasj
  • 49
  • 2
  • 8

1 Answers1

1

DynamicInvoke parameter uses the params object[] definition.

This means when you are passing an array of string[] to this function, each entry in the array of strings is a new parameter.

You are getting an exception because you cant cast a string to string[];

What you need to do is call DynamicInvoke like this.

commandHash["Test"].DynamicInvoke(new object[] { str });
Matthew
  • 639
  • 5
  • 11