9

Why i cannot declare default arguments for member functions of a managed type or generic functions? C# 4.0 introduced Named and Optional Arguments; there is a similar thing for CLI?

I do not understand why is not possible to declare a method like this:

void Optional(int argument = 0);

And then when I call Optional(); the compiler does not translate this call into: Optional(0);.

gliderkite
  • 8,828
  • 6
  • 44
  • 80

1 Answers1

11

It looks like the C++/CLI Compiler doesn't emit the correct IL directive for that. It doesn't emit the directive .param [1] = int32(0), which C# uses for recognizing default parameters. If you open the generated assembly in ILDasm, you'll see it.

A way that compiles would be to use the attributes Optional and DefaultParameterValue from the System::Runtime::InteropServices namespace, but C# doesn't use those for default parameters, so currently there's no easy way around creating an overload.

You can find the question asking about those Attributes here: https://stackoverflow.com/a/4974528/93652

Community
  • 1
  • 1
Botz3000
  • 39,020
  • 8
  • 103
  • 127
  • So the C++/CLI compiler doesn't know how to generate the directive. I hope that with VS (12 ?) the problem will be solved. – gliderkite Apr 25 '12 at 14:26
  • I hope so, too. Interestingly it seems that languages handle this differently. I heard VB.Net does it by using the Attributes. So i guess it would be best if both attributes and the directive were generated. – Botz3000 Apr 25 '12 at 14:28