Home > Back-end >  Optional ref parameters - Microsoft.Office.Word.Interoop
Optional ref parameters - Microsoft.Office.Word.Interoop

Time:06-15

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?

CodePudding user response:

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#.

CodePudding user response:

Here read this it may help you :) https://www.c-sharpcorner.com/blogs/ref-out-and-optional-parameters-in-c-sharp2

  • Related