C# language feature:

  • Named and optional arguments

applies to

  • method parameters

benefit

  • Named arguments are useful in making method calls self-documenting and reduce dependence on a parameter’s position in the parameter list.

how to use

  • 1) Named arguments - preceed argument passed with name of parameter and :
  • 2) Options arguments - must come after required arguments, and have default assignments.

example:

        void PrintName(string lastname,  string firstname, bool lastnamefirst=true)
        {
            if (lastnamefirst)
                System.Console.WriteLine(lastname + ", " + firstname);
            else
                System.Console.WriteLine(firstname + " " + lastname);
        }

        void Use_of_Named_Arguments_Example()
        {
            PrintName(firstname:"Jeff", lastname: "Doe");  // note parameter order does not matter, optional argument is true
            PrintName(lastname:"Doe", firstname:"Jeff");  // both print "Doe, Jeff"
        }