CRK CRK - 2 months ago 21
C# Question

COM Interop Method Signature with ByRef

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

with two parameters: the first parameter is passed
, the second one is passed

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
keyword, the compiler doesn't advice me that I missed the
keyword and passes the parameter
. This can be a big problem if I miss the
keyword because I can't notice it until I know that it wants the
. Do you know why the compiler exhibits this behavior?


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 :)