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
Loading
VulpesPosted Mar 24, 2014, 8:48 AM
and so is this:
displayName("John", "D");
Jignesh TrivediPosted Mar 24, 2014, 2:45 AM
hi,
Optional parameter has a default value as a part of its definition so when you are not passing any value it will take default value.
In your case, only firstname is compulsory middle name and last name is optional parameter.
so if you are not passing either of middle name or last name, function will take its default value.
I think this is correct behavior of optional parameter
http://msdn.microsoft.com/en-us/library/dd264739.aspx
Hope this will help you.