#584 – Defining an Optional Parameter

When you define a method in C#, you can define one or more of the method’s parameters as optional.  An optional parameter is one that has a default value, which allows a calling function to choose whether or not it wants to pass in a value for that parameter.  Any parameters that are omitted by the caller will take on the specified default value.

Here’s the Bark method of a Dog object, which supplies a default value for the numTimesToBark parameter, making it optional.

        public void Bark(string barkSound, int numTimesToBark = 1)
        {
            for (int i = 0; i < numTimesToBark; i++)
                Console.WriteLine(barkSound);
        }

When calling Dog.Bark, the caller can pass in a value for numTimesToBark, or leave off this argument so that the parameter uses the default value (1).

// Pass in both barkSound and numTimesToBark
myDog.Bark("Bow-wow", 4);

// Pass in only barkSound
myDog.Bark("Woof");

Advertisements

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

7 Responses to #584 – Defining an Optional Parameter

  1. Pingback: #585 – Optional Parameters Must Come Last « 2,000 Things You Should Know About C#

  2. Pingback: #586 – Default Values for Optional Parameters Must Be Constants « 2,000 Things You Should Know About C#

  3. Pingback: #589 – Optional Parameters Must Be Input Parameters « 2,000 Things You Should Know About C#

  4. Pingback: #590 – Optional Parameters in Constructors « 2,000 Things You Should Know About C#

  5. Pingback: #592 – Optional Parameters in Indexers « 2,000 Things You Should Know About C#

  6. Pingback: #594 – When You’d Want to Use Named Arguments « 2,000 Things You Should Know About C#

  7. Pingback: #816 – Named Argument and Optional Parameter Combinations | 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 )

Google+ photo

You are commenting using your Google+ 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: