#816 – Named Argument and Optional Parameter Combinations

You use named arguments (vs. positional) to reverse the order of arguments passed in to a method when you call it.

You use optional parameters (vs. required) to to allow omitting an argument for that parameter when you call the method.

Options include:

  • No named arguments, no optional parameters – you must pass in a value for each parameter, in the proper order
  • Named arguments only – you must pass in an argument for each parameter, but you can change the order of the arguments.  Named arguments must follow positional arguments.
  • Optional parameters only – you must pass arguments in the correct order, but may omit one or more arguments if the corresponding parameter is optional.  If you omit an argument for one parameter, you must omit arguments for all parameters that follow that parameter.
  • Named arguments and optional parameters – you can supply any combination of arguments, in any order

#815 – Named vs. Positional Arguments

C# supports the use of named arguments, in which you can change the order of arguments passed to a function, by prefixing an argument with the corresponding parameter name.

An argument that is not prefixed with the name of a parameter is considered a positional argument.

Positional arguments must come before named arguments and match the order of the corresponding parameters.

        // Sample method with 3 parameters
        public void Bark(int numTimes, string sound, double volume)

Below are some examples of using both named and positional arguments.

            // Example 1: All arguments are positional
            myDog.Bark(2, "Woof", 10.0);

            // Example 2: Only 1st argument is positional
            myDog.Bark(2, volume: 10.0, sound: "Woof");

            // Example 3: All arguments are named
            myDog.Bark(volume: 10.0, sound: "Woof", numTimes: 2);

#814 – Parameters vs. Arguments

A parameter is a variable name for a piece of data passed into or out of a method.    The parameter is the name by which that piece of data is referred to within the body of the method.  Parameters are listed as part of a method’s declaration, within the parentheses that follow the method’s name.

You specify a parameter by indicating the type of the parameter and its name.

        // Bark has 4 parameters
        public void Bark(int numTimes, string sound, ref int globalBarkCount, out bool didBark)

An argument is a constant or variable name passed to a method.  Each argument maps to one of the method’s parameters.

When you specify an argument, you specify the value that will be passed to the method or a variable containing the value.

            // 4 arguments passed to Bark method
            myDog.Bark(2, "Woof", ref globCount, out didBark);

#808 – Adding Parameters to an Extension Method

When you define an extension method, the first parameter of your method represents the instance that you want the method to act upon.  You can, however, add additional parameters.

An extension method that acts on a string, for example, would have string as the first parameter and then, optionally, some other parameters.

        public static string Decorate(this string s, string frontDec, string backDec)
        {
            return frontDec + " " + s + " " + backDec;
        }

When you invoke the method, you pass in these additional parameters.

            // Using the extension method
            string s = "Salk announces polio vaccine";
            string dec = s.Decorate("<<==", "==>>");
            Console.WriteLine(dec);

808-002

Notice that Intellisense now lists the new extension method as an option for the string type and correctly lists two parameters.
808-001

#802 – A Method Might Have No Parameters

You can pass one or more data values to a method using parameters.  A parameter in a method is just a variable, usable only within that method, that refers to a piece of data passed into the method.

If the method that you are writing requires no data to be passed in, you can omit all parameters.  You include an empty pair of parentheses after the method name, to indicate that the method has no parameters.

    public class Dog
    {
        public string Name { get; set; }
        public int Age { get; set; }

        // All data that we need is passed into constructor
        public Dog(string name, int age)
        {
            Name = name;
            Age = age;
        }

        // Bark is a method that has no parameters
        public void Bark()
        {
            Console.WriteLine(string.Format("{0} : WOOF !", Name));
        }
    }

#587 – If Provided, Optional Arguments Must Be in Correct Order

When you choose to include arguments for optional parameters on a method, you must specify the arguments in the proper order (just like required parameters).

In the example below, we define a method with one required parameter and three optional parameters.  When we call it, we must provide a value for the yourName parameter.  Then we can provide values for one, two or all three of the optional parameters, in the following combinations:

  • book
  • book, play
  • book, play, poem
        static void Favorites(
            string yourName,
            string book = "Moby Dick",
            string play = "Henry V",
            string poem = "The Road Not Taken")
        {
            Console.WriteLine("{0}'s favorites:", yourName);
            Console.WriteLine("  Book: {0}", book);
            Console.WriteLine("  Play: {0}", play);
            Console.WriteLine("  Poem: {0}", poem);
        }

        static void Main()
        {
            Favorites("Sean");
            Favorites("Sergei", "Anna Karenina");
            Favorites("Pablo", "Don Quixote", "Canción de cuna");
            Favorites("Nigel", "David Copperfield", "Hamlet", "Ode to Duty");
        }

#585 – Optional Parameters Must Come Last

If you define a method that includes optional parameters, they must come after any required parameters.  This means that your options for required vs. optional parameters are:

  • No parameters at all
  • 1 or more required parameters (no default values)
  • 1 or more optional parameters (with default values)
  • 1 or more required parameters, followed by 1 or more optional parameters
        static void NoParams() { }
        static void RequiredOnly(int x, int y) { }
        static void OptionalOnly(int x = 5, int y = 10) { }
        static void RequiredAndOptional(int x, int y, int a = 1, int b = 2) { }

        static void Main()
        {
            NoParams();
            RequiredOnly(5, 10);

            OptionalOnly();
            OptionalOnly(1);
            OptionalOnly(1, 2);

            RequiredAndOptional(1, 1);
            RequiredAndOptional(1, 2, 3);
            RequiredAndOptional(1, 2, 3, 4);
        }