Link to home
Start Free TrialLog in
Avatar of brgdotnet
brgdotnetFlag for United States of America

asked on

Ambiguous optional parameters

Can someone help me with the topic of optional parameters in C#. Please look at line 14 below. The value  is being sent to the method SendEmail. So my question is that on line 14  ""

is preceded by fromAddress :  on line 14. So why is it preceded by the variable name? That seems rather unecessary. Look at line 121 I have removed the "fromAddress  :"

in the parameter list and it works just fine.

public bool SendEmail(int Id, bool OverrideFromAddress, string fromAddress = "")
    return true;

11  private void InitializeComponent()
12  {
13   this.button1 = new System.Windows.Forms.Button();

14 SendEmail(5, OverrideFromAddress : true,  fromAddress : "");

121 SendEmail(5, OverrideFromAddress : true,   "");

Avatar of Alex [***Alex140181***]
Alex [***Alex140181***]
Flag of Germany image

You could also write this:
SendEmail(5, true, "");

Open in new window

Specifying the parameter allows you to control the ordering of your parameters and really nothing more.  There is no benefit to doing this and can confuse other developers who follow you.  As stated above, you can simply call the method with the values in the method's defined parameter order without needing to identify which parameter each value belongs to.

As for optional parameters, if you do not specify a value for any optional parameters then the value specified is used.  With that being stated the following would be valid as well:
SendEmail(5, true);

Open in new window

Your method will simply assign an empty string to the fromAddress parameter.

Avatar of louisfr

Link to home
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial