CRK CRK - 26 days ago 12
C# Question

COM Interop Method Signature with ByRef

I have a C# program that calls a COM DLL that has a method called

test
with two parameters: the first parameter is passed
ByVal
, the second one is passed
ByRef
.

This is what the COM DLL does:

Public Sub test(ByVal a As String, ByRef b As String)
a = "a"
b = "b"
End Sub


This is what C# program does:

test.Class1 x = new test.Class1();
string a = "1";
string b = "2";
x.test(a, ref b);


I notice that if I remove
ref
keyword, the compiler doesn't advice me that I missed the
ref
keyword and passes the parameter
ByVal
. This can be a big problem if I miss the
ref
keyword because I can't notice it until I know that it wants the
ref
. Do you know why the compiler exhibits this behavior?

Answer

This is highly specific to COM interop code and C# language version 4 and up. Yes, it permits omitting ref in this specific case. C# version 4 had a lot of tweaks to make Office programming easier. The Office api was originally designed to work well with early VB versions, they used ByRef by default. Still the case for VBA. So the api has a lot of method parameters that are ByRef, even though they don't actually modify the passed argument.

The compiler will generate a temporary variable if necessary to make the call legal. With the consequence that your variable doesn't get updated. Something you'll have to watch out for. Two steps forward, one step back :)