What's the difference between
Method(int arg0 = 0) vs Method([Optional] int arg0 = 0);
whenever I'm trying to invoke this method compiler says its ambiguous situation. I know why it is ambiguous situation, my interest is whats the difference between those 2 if they facilitating the same thing = optional parameter. However they do so in a different way, at list visually - don't know about under the hood.
It was pointed out to me that first way is really for DEFAULT use, meaning you would initialize default values while second one is OPTIONAL that it used in cases when you will not define any default values - while it make sense, however they both can be easily have assigned values and not. Whats the real difference and use of them?
The OptionalAttribute
is automatically applied by the compiler when you specify an optional parameter, basically. (It's a bit like ExtensionAttribute
being supplied for extension methods.)
In IL, it doesn't appear like other attributes - it just has [opt]
before the parameter.
I would advise you not to explicitly specify it yourself - use the language-provided mechanism instead.
Note that you can specify a default value using DefaultParameterValueAttribute
too. So these two declarations are equivalent:
void Foo(int x = 5)
void Foo([Optional, DefaultParameterValue(5)] int x = 5)
The fact that these attributes exist allows languages which don't explicitly support them to still express them - so you could write a C# 2 program which exposed methods with optional parameters for consumption in VB, for example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With