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?
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.
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.
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.
C# and Java are often considered examples of statically typed languages, while Python, Ruby and JavaScript are examples of dynamically typed languages.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With