Friday 5 June 2015

Optional Parameters

Previously we talked about overloading which was the concept of having functions with the same name but different signatures, then depending on the arguments passed to the function the corresponding function would be called. Before that we spoke of named parameters, which let us choose the order we input our parameters to functions, methods or constructors. Now we're going to talk about optional parameters, which can help minimize the number of overloaded functions required, there are appropriate and inappropriate situations as to when to leverage these, and it's really up to you to decide when it's right in your code.


namespace pav.optionalArguments;
class Program
{

    public static void printName(string first, string last, bool isMale,  string middle = "", bool isMarried = false, bool isDoctor = false)
    {
        var prefix = isDoctor ? "Dr." : isMale ? "Mr." : isMarried ? "Mrs." : "Ms.";
        middle = String.IsNullOrEmpty(middle) ? " " : $" {middle} ";

        Console.WriteLine($"{prefix} {first}{middle}{last}");
    }

    static void Main(string[] args)
    {
        // no optional parameters needed
        printName("Robert", "Smith", true);

        // all parameters needed
        printName("Jessica",  "Johnson", false, "Lyne", true, true);
                 
        // mix of named and optional paramters
        printName("Megan", "Jones", middle: "Eli", isMale: false, isMarried: true);

        //named paramteres not needed, but position matters
        printName("Tom", "Williams",
                  isMale: true, isMarried: true, isDoctor: true);

        // jumbled parametar input
        printName("Kristy", "Gray", middle: "Grace", isMale: false);

        // some sort of logic behind named parametars
        printName("Amanda", "Harding", isDoctor: true, isMale: false);
    }
}


By leveraging optional parameters we can minimize the number of function declarations needed, Optional parameters in combination with Named parameters can  also simplify our method calls making our code more readable.