Geetha Gubendran

Geetha Gubendran

  • NA
  • 11
  • 11.3k

Query on Optional Parameter

Mar 23 2014 10:26 PM
In Wrox book, I found the following statement and example for optional parameter
the caller must provide a value for the first parameter but can exclude the initial and
last. However, if the caller provides a value for last, it must also provide a value for the initial. If a value for the initial is passed, a value for the last name is still optional, however.


public void displayName(string first, string initial = "", string last = "")
{
Console.WriteLine(first + " " + initial + " " + last);
}

So, I wrote the example to test the same.

public string printFullName(string firstName,string middleName="",string lastName="")
{
return "FullName =>"+firstName + middleName + lastName;
}

My caller is the below code

string fullName = p.printFullName(firstName:"FirstName",lastName:"LastName");
Console.WriteLine("Testing Named Parameter: "+fullName);

As per the above statement from the book, if I pass the lastName and not the middleName, the compiler has to throw an error.
But I am getting the output as "FirstNameLastName" without any error.
Am I understanding anything wrong here.

I thought it this way as well. Bcos there is a default value for middlename, it doesnt throw the error. but I think providing default value for the parameter represents the optional parameter. Is it not? If so what is the meaning of the statement from the book above?

Note: I tried giving just firstName and middleName without lastName, then also the system outputs the message. But as per the statement from the book, its acceptable.

Thanks,
Geetha


Answers (2)