Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use "Optional, DefaultParameterValue" attribute, or not?

Tags:

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"); 
like image 406
Koray Avatar asked Oct 21 '16 07:10

Koray


People also ask

How do you pass an optional argument in C#?

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 is the use of optional parameter?

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.

Is a optional parameter in?

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.

Why are optional parameters bad?

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.


Video Answer


1 Answers

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.

like image 90
Marc Gravell Avatar answered Sep 28 '22 03:09

Marc Gravell