#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
Advertisement

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

#593 – Using Named Arguments

Traditionally in C#, arguments must be passed in to a method in the same order in which they are defined in the method’s declaration.

public void DoATrick(string trickName, int numTimes)
            Dog kirby = new Dog("Kirby");

            kirby.DoATrick("Fetch", 158);

You can, however, change the order of the arguments by preceding each value by the name of the parameter, with a colon (:) following each name.

            kirby.DoATrick(numTimes: 5, trickName: "Run around me");

#340 – Use the params Keyword to Pass a Variable Number of Arguments

When you define a method in a class, the parameters of the method normally dictate the exact number of arguments that you can pass to the method.  There are times, however, when you might want to pass a variable number of parameters to a method.

You could pass a variable number of parameters to a method by using an array.

        public void PerformCommands(string[] commandList)
        {
            foreach (string command in commandList)
                Console.WriteLine("Ok, I'm doing [{0}]", command);
        }

You’d call this method by creating a new instance of an array.

            kirby.PerformCommands(new string[] { "Sit", "Stay", "Come" });

To simplify things, you can use the params keyword in the method definition.  This allows passing the elements of the array as individual arguments.

        public void PerformCommands(params string[] commandList)

This makes calling the method a little cleaner.

            kirby.PerformCommands("Sit", "Stay", "Come", "Fetch");

#13 – Specify Command Line Arguments in Visual Studio 2010

You’d normally pass command line arguments to your program when you invoke it from the command line.  However, for testing purposes, you may want to specify command line arguments that get passed to the program when you run it from the debugger.  You can do this in the Project Properties window, on the Debug tab.

Note that:

  • You can do this for all project types, e.g. console app, Win Forms, WPF
  • You can specify different arguments for Debug vs. Release mode
  • These arguments will be used only when running from the debugger

#12 – Read Command Line Arguments

If you are calling your C# program from the command line, you can pass in one or more command line arguments.  In your program, you can access these arguments by defining the Main function to accept a string array as a parameter and then iterating through the array to read the parameters.

static void Main(string[] args)
{
    // Ex 1: List all arguments
    foreach (string arg in args)
        Console.WriteLine(string.Format("Arg: [{0}]", arg));

    // Ex 2: Use 1st argument as filename
    if (args.Length > 0)
        Console.WriteLine(string.Format("File={0}", args[0]));
}

#6 – An Even Smaller C# Program

In The Smallest Possible C# Program, I mentioned a couple things as optional.  For the record, here’s the absolute smallest C#.NET program that you can write.  (Assuming that you don’t need it to actually do anything).

class Program
{
    static void Main()
    {
    }
}

#2 – The Smallest Possible C# Program

The smallest possible C# program would consist of a static Main() function inside of a class. The namespace is actually optional, as is the args parameter.

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("2,000 Things Was Here..");
        }
    }
}