9

Similar to this, but with a twist.

VB function declaration:

Public Shared Function MyFunc(ByVal Name As String, ByVal Num As Integer, Optional ByRef obj As Object = Nothing, Optional ByVal val As Integer = 0) As Boolean

When calling in C# (different solution, I copied over the .dll)

Error 164 No overload for method 'MyFunc' takes 2 arguments

Metadata shows the function to be:

public static bool MyFunc(string Name, int Num, ref object obj, int val = 0);

Why did one Optional make it through while the other didn't?

Community
  • 1
  • 1
JNF
  • 3,696
  • 3
  • 31
  • 64

2 Answers2

10

C# doesn't support optional ref parameters. If you change obj to be a ByValue parameter, it should be fine.

If you try to declare an optional ref parameter in C#, you'll violate section 10.6.1 of the C# 4 spec:

A fixed-parameter with a default-argument is known as an optional parameter.

...

A ref or out parameter cannot have a default-argument.

The exception to this is for COM, where ref parameters are extremely common. When the C# compiler knows it's dealing with a COM component, it will allow you to omit optional ref parameters.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Out of curiosity, I swapped the order of the last two parameters, the C# project didn't have a problem accepting that, though the metadata was `public static bool MyFunc(string Name, int Num, int val = 0, ref object obj);` which is illegal. When trying to pass 2 parameters I got the `No overload...takes 2 arguments`. When trying to pass 3 parameters I got the `No overload...takes 3 arguments`. Interesting. – JNF Jul 18 '13 at 08:14
  • @JNF: The metadata you're showing is only a C# *representation* of whatever's in the IL. I suspect the real metadata for the original version was fine too - it's just that whatever you're using to translate that metadata into C# didn't work out what to do. I wouldn't just change the order of the parameters though - if that happens to work now, it's no guarantee that it will in the future. I'd change the signature to something which is also representable in C#. – Jon Skeet Jul 18 '13 at 08:17
  • no, well, that was just me playing Curious George. I ended up overloading in the VB. – JNF Jul 18 '13 at 08:18
5

C# doesn't allow by-ref optional parameters. That's the reason.

See this other question+answer:

Community
  • 1
  • 1
Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206