Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic Keyword, C# and Interop?

Ok, I am calling an interop dll which I have no access to. Here is the pseudo code:

dynamic myVariable = null;

firstInteropMethod(ref myVariable);
secondInteropMethod(myVariable); //Not by ref

The method signatures for the two methods are

firstInteropMethod(ref object someObject);
secondInteropMethod(object someObject);

The expected value is a double array of the definition

double[,]

Now the fun part. My original code gets the wrong results but no error. However, this code:

firstInteropMethod(ref myVariable);
secondInteropMethod((double[,]) myVariable);

Gives the expected results.

Using watches and type of statements I have determined that nothing changes between the two calls so what gives? Why would there be a difference and what would that difference be?

like image 467
Synxmax Avatar asked May 18 '11 10:05

Synxmax


People also ask

What is C# dynamic keyword?

The dynamic keyword is new to C# 4.0, and is used to tell the compiler that a variable's type can change or that it is not known until runtime. Think of it as being able to interact with an Object without having to cast it.

What is the use of dynamic keyword?

It is used to avoid the compile-time type checking. The compiler does not check the type of the dynamic type variable at compile time, instead of this, the compiler gets the type at the run time. The dynamic type variable is created using dynamic keyword.

What is static and dynamic keyword?

A static (not to be confused with the static keyword, used for classes) typed language validates the syntax or checks for any errors during the compilation of the code. On the other hand, dynamically typed languages validate the syntax or checks for errors only at run time.

Is C sharp dynamic or static?

C# and Java are often considered examples of statically typed languages, while Python, Ruby and JavaScript are examples of dynamically typed languages.


1 Answers

This MSDN article on dynamic explains why casting is needed for COM Interop when operations declare the parameter type as object and indicates that using the /link:filelist compiler option will allow you to define the COM method signatures as dynamic as well.

like image 94
Ethan Cabiac Avatar answered Sep 29 '22 02:09

Ethan Cabiac