#587 – If Provided, Optional Arguments Must Be in Correct Order
May 21, 2012 1 Comment
When you choose to include arguments for optional parameters on a method, you must specify the arguments in the proper order (just like required parameters).
In the example below, we define a method with one required parameter and three optional parameters. When we call it, we must provide a value for the yourName parameter. Then we can provide values for one, two or all three of the optional parameters, in the following combinations:
- book
- book, play
- book, play, poem
static void Favorites( string yourName, string book = "Moby Dick", string play = "Henry V", string poem = "The Road Not Taken") { Console.WriteLine("{0}'s favorites:", yourName); Console.WriteLine(" Book: {0}", book); Console.WriteLine(" Play: {0}", play); Console.WriteLine(" Poem: {0}", poem); } static void Main() { Favorites("Sean"); Favorites("Sergei", "Anna Karenina"); Favorites("Pablo", "Don Quixote", "Canción de cuna"); Favorites("Nigel", "David Copperfield", "Hamlet", "Ode to Duty"); }