Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot deconstruct dynamic object while calling dll's method

Say I have some dll with a method like so:

public (string, List<string>) MyMethod(NameValueCollection Settings, MyClass1 params)
{
 //do something
 return (result, errorList);
}

Now from my main project I will call it like so:

var shipmentNumber = string.Empty;
var errorList = new List<string>;
var DLL = Assembly.LoadFile($@"{AppDomain.CurrentDomain.BaseDirectory}{appSettings[$"{parameters.TestCase}_DLL_Name"]}");
Type classType;
classType = DLL.GetType($"{appSettings[$"{parameters.TestCase}_DLL_Name"].Replace(".dll", "")}.MyService");
dynamic d = Activator.CreateInstance(classType);
(result, errorList)= d.MyMethod(appSettings, params);

However this gives me an error on the last line shown here Cannot deconstruct dynamic objects. Is there a way I could return tuple properly here?

like image 260
Yuropoor Avatar asked Dec 03 '22 19:12

Yuropoor


1 Answers

As per the compiler error message, you can't use deconstruction with dynamic values.

In this case you know that your method is going to return a tuple, so either cast the result to that:

(result, errorList) = ((string, List<string>)) d.MyMethod(appSettings, params);

Or assign to a tuple and then deconstruct:

(string, List<string>) tuple = d.MyMethod(appSettings, params);
(result, errorList) = tuple;

Note that the casting looks a bit funky with the double parentheses, but they're necessary: the outer parentheses are for casting syntax; the inner parentheses are for tuple type syntax.

Here's a complete simple example:

using System;

class Test
{
    static void Main()
    {
        dynamic d = new Test();

        // Variables we want to deconstruct into
        string text;
        int number;

        // Approach 1: Casting
        (text, number) = ((string, int)) d.Method();

        // Approach 2: Assign to a tuple variable first
        (string, int) tuple = d.Method();
        (text, number) = tuple;

    }

    public (string, int) Method() => ("text", 5);
}
like image 61
Jon Skeet Avatar answered Dec 06 '22 09:12

Jon Skeet