#590 – Optional Parameters in Constructors

You’ll typically see optional parameters in methods.  But you can also define an optional parameter in a constructor:

        public string Name { get; set; }
        public int Age { get; set; }
        public string FavoriteToy { get; set; }
        public Dog Father { get; set; }
        public Dog Mother { get; set; }

        public Dog(string name, int age = 1, string favToy = "Bone",
            Dog father = null, Dog mother = null)
            Name = name;
            Age = age;
            FavoriteToy = favToy;
            Father = father;
            Mother = mother;


            Dog kirby = new Dog("Kirby", 15, "Ball");
            Dog sonOfKirby = new Dog("Ferbie", 2, "Frisbee", kirby);

Optional parameters in constructors avoid the need to chain constructors.



#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++)

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