Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between Default and [Optional] Parameters?

Tags:

c#

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?

like image 217
Ailayna Entarria Avatar asked Feb 21 '14 09:02

Ailayna Entarria


1 Answers

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.

like image 157
Jon Skeet Avatar answered Nov 16 '22 02:11

Jon Skeet