#584 – Defining an Optional Parameter
May 16, 2012 7 Comments
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");
Pingback: #585 – Optional Parameters Must Come Last « 2,000 Things You Should Know About C#
Pingback: #586 – Default Values for Optional Parameters Must Be Constants « 2,000 Things You Should Know About C#
Pingback: #589 – Optional Parameters Must Be Input Parameters « 2,000 Things You Should Know About C#
Pingback: #590 – Optional Parameters in Constructors « 2,000 Things You Should Know About C#
Pingback: #592 – Optional Parameters in Indexers « 2,000 Things You Should Know About C#
Pingback: #594 – When You’d Want to Use Named Arguments « 2,000 Things You Should Know About C#
Pingback: #816 – Named Argument and Optional Parameter Combinations | 2,000 Things You Should Know About C#