Sixto Saez
Sixto Saez

Reputation: 12680

How is a method with out parameters assigned to an ExpandoObject?

I'm trying to assign a method (function) to an ExpandoObject with this signature:

public List<string> CreateList(string input1, out bool processingStatus)
{
  //method code...
}

I've tried to do something like this code below which doesn't compile:

dynamic runtimeListMaker = new ExpandoObject();
runtimeListMaker.CreateList =
     new Func<string, bool, List<string>>(
           (input1, out processingStatus) =>
                {
                     var newList = new List<string>();

                     //processing code...

                     processingStatus = true;
                     return newList;
                });

Unfortunately I cannot change the CreateList signature because it will break backward compatibility so rewriting it is not an option. I've tried to get around this by using delegates but at runtime, I got an "Cannot invoke a non-delegate type" exception. I guess this means I'm not assigning the delegate correctly. I need help getting the syntax correct (delegate examples are OK too). Thanks!!

Upvotes: 1

Views: 928

Answers (2)

Homam
Homam

Reputation: 23871

The problem in your code that using out parameter type for processingStatus parameter which is not allowed in C#.

Upvotes: 0

Tejs
Tejs

Reputation: 41266

This sample compiles and runs as expected:

dynamic obj = new ExpandoObject();
obj.Method = new Func<int, string>((i) =>
    {
        Console.WriteLine(i);
        return "Hello World";
    });

obj.Method(10);
Console.ReadKey();

The problem with your statement is that your Func does not use an output parameter like your signature does.

(input1, out processingStatus)

If you want to assign your current method, you won't be able to use Func, but you CAN create your own delegate:

    public delegate List<int> MyFunc(int input1, out bool processing);

    protected static void Main(string[] args)
    {
        dynamic obj = new ExpandoObject();
        obj.Method = new MyFunc(Sample);

        bool val = true;
        obj.Method(10, out val);
        Console.WriteLine(val);
        Console.ReadKey();
    }

    protected static List<int> Sample(int sample, out bool b)
    {
        b = false;
        return new List<int> { 1, 2 };
    }

Upvotes: 5

Related Questions