Optional parameters in managed C++/CLI methods

As a workaround, you can just overload the constructor, and use delegation. It will be inlined by the JIT and should end up with the same final result as a default parameter value.


The C# compiler doesn't use the [DefaultParameterValue] attribute to set the default value, it uses the .param directive to get the value embedded in the metadata. Barely documented in the CLI spec btw, only Partition II, chapter 15.4.1 mentions that it can have a FieldInit value, 15.4.1.4 is silent about it.

That's where the buck stops, the C++/CLI compiler doesn't know how to generate the directive. You cannot make this work.


There is a trick to make this working (workaround). the magic word is nullable, as for nullable types the default is always "null" (.HasValue == false).

Example:

C++ CLI in header:

String^ test([Optional] Nullable<bool> boolTest);

C++ CLI in .cpp file:

String^ YourClass::test(Nullable<bool> boolTest)
{
    if (!boolTest.HasValue) { boolTest = true; }
    return (boolTest ? gcnew String("True") : gcnew String("False"));
}

to Test it in C#:

MessageBox.Show(YourClass.test());

Note that [Optional] in the example above is located in the namespace System::Runtime::InteropServices. To access it, add the following line:

using namespace System::Runtime::InteropServices;