What is the difference between Default and [Optional]?

What's the difference between

Method(int arg0 = 0) vs Method([Optional] int arg0 = 0); 

whenever I try to call this method, the compiler talks about its ambiguous situation. I know why this is an ambiguous situation, my interest is what is the difference between these 2 if they facilitate the same thing = optional parameter. However, they do it differently, visually on the list - they donโ€™t know about under the hood.

I was told that the first method is really used to use DEFAULT, which means that you initialize the default values, and the second - OPTIONAL, which were used in cases where you will not define the default values โ€‹โ€‹- although this makes sense, however they both can be easily assigned to values, rather than. What is the real difference and their use?

+7
c #
source share
1 answer

OptionalAttribute automatically applied by the compiler when you specify an optional parameter, basically. (This is a bit like ExtensionAttribute for extension methods.)

In IL, this is not like other attributes - it has [opt] before the parameter.

I would advise you not to directly specify it yourself - use the mechanism provided by the language instead.

Note that you can specify a default value using DefaultParameterValueAttribute . 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 โ€‹โ€‹that do not explicitly support them to express them yet - so you could write a C # 2 program that opens methods with optional parameters for consumption in VB, for example.

+15
source share

All Articles