Dynamic type in method parameter

I am passing a dynamic type to a method and have some problems running the code. Wondering if you can pass a dynamic object as a parameter using the out keyword.

Below is the code.

dynamic btApp = AutomationFactory.CreateObject("Test.Application");
dynamic btMessages;

dynamic btFormat = btApp.Formats.Open("c:\\Temp/Format1.btw", false, "");
btFormat.SetNamedSubStringValue("testing", "testtest");
btFormat.Print("Job1", true, -1, out btMessages);
btFormat.Close(2);

      

the problem is the printing method. where the last argument is passed in a dynamic object.

+1


source to share


2 answers


It depends on what the actual type signature of the method is Print

. The type dynamic

is represented as object

at runtime, so if the method Print

takes a out

type parameter object

(or dynamic

) then it should work.



If the method Print

has an actual parameter of a out

different type, then the actual runtime type used on the caller's side does not match the actual type of the declaration, so it will not work.

0


source


When you pass an out parameter to a method with a variable of type dynamic, the parameter itself must be of type dynamic. The following code is legal:

class Program {
    static void Main(string[] args) {
        dynamic value;
        SomeMethod(out value);
        return;
    }
    static void SomeMethod(out dynamic value) {
        value = "5";
        return;
    }
}

      



In fact, SomeMethod can assign a value to anything. When the parameter is not of type dynamic, the compiler tries to convert before calling the method, which is not allowed, so if the parameter in SomeMethod is something that is not dynamic, you are out of luck.

+1


source







All Articles