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 CustomRelations@ourcustomsite.com  is being sent to the method SendEmail. So my question is that on line 14  "CustomRelations@ourcustomsite.com"

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();
this.SuspendLayout();

14 SendEmail(5, OverrideFromAddress : true,  fromAddress : "CustomRelations@ourcustomsite.com");


121 SendEmail(5, OverrideFromAddress : true,   "CustomRelations@ourcustomsite.com");

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

You could also write this:
SendEmail(5, true, "CustomRelations@ourcustomsite.com");

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.

-saige-
ASKER CERTIFIED SOLUTION
Avatar of louisfr
louisfr

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