#587 – If Provided, Optional Arguments Must Be in Correct Order

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");
        }

Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #587 – If Provided, Optional Arguments Must Be in Correct Order

  1. Pingback: #693 – Named Arguments in Constructors Allow the Most Flexibility « 2,000 Things You Should Know About C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: