0

I'm writing a C++/CLI library which is supposed to be used by C# (managed) applications.

I want to write a method which accepts optional parameters, which in C# would be written as:

void Function (object obj, object opt1 = null, int opt2 = 0)

When writing such a thing in C# indeed shows the same thing in the Intellisense.

In C++/CLI I write in the header file:

void Function (Object^ obj, [Optional] Object^ opt1 , [Optional] int opt2);

After compiling my library I get in the C# Intellisense the following function:

void Function (object object, object opt1 = bad value, int opt2 = bad value)

Remark: I understand that the default value can not be changed to anything other than "default(TYPE)", so I don't even try.

EZLearner
  • 1,614
  • 16
  • 25

1 Answers1

1

The C# team was very reluctant to add optional parameters as a language feature. They caved in to popular demand at version 4, Office programming in particular is quite brutal without it.

More than one problem with the feature, the one that matters in this case is that the feature is very strongly tied to the language. Optional and default parameters work very differently in C++. Optional parameters are encoded with ... in the method signature (think printf), default parameter values are a pure compiler feature in the language, the default value is normally retrieved from the function declaration in a .h file. And defeated when you try to use it on a ref class method with C3222, the implementers knew that it wasn't going to work back in 2005 and the language has been in maintenance mode since.

What is missing is the default parameter value, the C++/CLI compiler doesn't generate one so the metadata decompiler can't show anything but "bad value". Not like it can't work, you get Type::Missing in the C++/CLI code in your specific case. Which although descriptive might seem bizarre, it is not nullptr like you might assume from default(T). But is compatible with Office interop.

Really rather best to avoid this in interop code. Consider method overloads.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536