Is there any difference between using Optional
and DefaultParameterValue
attributes and not using them?
public void Test1([Optional, DefaultParameterValue("param1")] string p1, [Optional, DefaultParameterValue("param2")] string p2) { } public void Test2(string p1= "param1", string p2= "param2") { }
both work:
Test1(p2: "aaa"); Test2(p2: "aaa");
Optional arguments enable you to omit arguments for some parameters. Both techniques can be used with methods, indexers, constructors, and delegates. When you use named and optional arguments, the arguments are evaluated in the order in which they appear in the argument list, not the parameter list.
What are Optional Parameters? By definition, an Optional Parameter is a handy feature that enables programmers to pass less number of parameters to a function and assign a default value.
A method that contains optional parameters does not force to pass arguments at calling time. It means we call method without passing the arguments. The optional parameter contains a default value in function definition. If we do not pass optional argument value at calling time, the default value is used.
The thing with optional parameters is, they are BAD because they are unintuitive - meaning they do NOT behave the way you would expect it. Here's why: They break ABI compatibility ! so you can change the default-arguments at one place.
They compile identically, and the compiler works fine with either. The only difference is the lack of using System.Runtime.InteropServices;
, and easier to read code.
For reference, the IL is:
.method public hidebysig instance void TheName([opt] string p1, [opt] string p2) cil managed { .param [1] = string('param1') .param [2] = string('param2') .maxstack 8 L_0000: ret }
where TheName
is the only thing that changes.
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