Avatar of brgdotnet
brgdotnet
Flag 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");

C#

Avatar of undefined
Last Comment
louisfr

8/22/2022 - Mon
Alex [***Alex140181***]

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

Open in new window

it_saige

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
louisfr

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck