Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional VB Parameters are required in C#

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?

like image 518
JNF Avatar asked Jul 18 '13 08:07

JNF


1 Answers

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.

like image 94
Jon Skeet Avatar answered Oct 05 '22 22:10

Jon Skeet