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

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