1

As far as I know, optional ref parameters aren't available in C#. Overloading is the closest you can get. You also have to pass ref parameters with ‘ref’ keyword.

At least that’s what I thought when I found this piece of code:

var doc = app.Documents.Open(inputFileFullPath, ReadOnly: true);

The strange thing about it is that when you hover over it, you'll see the following:

enter image description here

The definition (from meta data) seems to be single method with ref parameters (no overloading or whatnot):

[DispId(19)]
Document Open(ref object FileName, ref object ConfirmConversions, ref object ReadOnly, ref object AddToRecentFiles, ref object PasswordDocument, ref object PasswordTemplate, ref object Revert, ref object WritePasswordDocument, ref object WritePasswordTemplate, ref object Format, ref object Encoding, ref object Visible, ref object OpenAndRepair, ref object DocumentDirection, ref object NoEncodingDialog, ref object XMLTransform);

And yet, the method doesn’t require ‘ref’ keyword, still allowing it (cast to object is required), and allows ref parameters to be optional:

var redonlyObj = (object)true;
var doc = app.Documents.Open(inputFileFullPath, ReadOnly:ref redonlyObj); //builds with no errors

Can anybody please explain to me what is going on here?

Piotrek
  • 169
  • 3
  • 17
  • There's a fair bit of documentation, probably starting here on [Optional Arguments with COM](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/named-and-optional-arguments#com-interfaces) which discusses the various changes made to C# back in *version 4* to simplify calling COM interfaces, and especially making mention of Office Interop. – Damien_The_Unbeliever Jun 15 '22 at 13:11
  • 2
    "As far as I know, optional ref parameters aren't available in C#" - _yes-and-no_: Since C# 4.0 it's possible to consume libraries (namely COM libs) with optional `ref` parameters, but C# still cannot _define_ or compile methods with optional `ref` parameters. – Dai Jun 15 '22 at 13:13
  • 1
    Instead of looking at the C#-syntax disassembly, look at the actual IL declaration. – Dai Jun 15 '22 at 13:14

1 Answers1

0

C# only supports a subset of the features supported by the .NET Framework (or, to be precise, by the Common Intermediate Language).

Declaring methods with optional ref parameters is one of them. Another example would be properties with parameters.

Both of these examples are supported in VB.NET, but not in C#.

Heinzi
  • 167,459
  • 57
  • 363
  • 519