C# 4.0 Optional Parameters

C# 4.0 introduces the concepts of Optional Parameters and the related Named Parameters language features. Essentially by giving parameters a default value, callers can omit values for those parameters. The example code below produces the following output:

 name: Peter age: 44 height: 200
NAME: PETER AGE: 44 YEARS HEIGHT: 200 CM
NAME: PETER AGE: 44 YEARS HEIGHT: 200 CM
NAME: PETER AGE: 44 YEARS HEIGHT: 200 CM
NAME: PETER AGE: 44 HEIGHT: 200

The code that produces this output:

class Program
{
    static void Main(string[] args)
    {
        // Supply all parameters explicity (passing false)
        Console.WriteLine(CreateString("Peter", 44, 200, false, false));

        // Supply all parameters explicity (passing true)
        Console.WriteLine(CreateString("Peter", 44, 200, true, true));

        // Supply only minimum required parameters,
        // the defaults (true) for useUpperCase & appendUnitText will be used
        Console.WriteLine(CreateString("Peter", 44, 200));

        // Supply the first optional parameter only
        Console.WriteLine(CreateString("Peter", 44, 200, true));

        // If we want to use the default for the first optional parameter (useUpperCase),
        // but we want to supply a value for the second optional parameter we
        // can use Named Parameters using the appendUnitText:false syntax
        Console.WriteLine(CreateString("Peter", 44, 200, appendUnitText:false));

        Console.Read(); // wait for enter key to be pressed
    }

    static string CreateString(string name,
                                int age, int height,
                                bool useUpperCase = true,
                                bool appendUnitText = true)
    {
        StringBuilder sb = new StringBuilder();
           
        sb.AppendFormat("name: {0} ", name);

        sb.AppendFormat("age: {0} ", age);
        if (appendUnitText)
            sb.Append("years ");

        sb.AppendFormat("height: {0} ", height);
        if (appendUnitText)
            sb.Append("cm ");

        if (useUpperCase)
            return sb.ToString().ToUpper();
        else
            return sb.ToString();               
    }
}

Add comment

Loading