Life is change. Growth is optional. Choose wisely.
Karen Kaiser Clark

It horrifies me that ethics is only an optional extra at Harvard Business School.
Sir John Harvey

What our children have to fear is not the cars on the highways of tomorrow but our own pleasure in calculating the most elegant parameters of their deaths.
J. G. Ballard

Option, Option,… Choice just does not have the same rhythm as Duck, Duck, … Goose.  This blog entry will show some new features in C# 4.  These features are optional parameters and named parameters.  Frequently, they are used together.

In C# 3, we could create multiple methods with different parameter signatures.  This simulates optional parameters but we do not know what the options are when using the different methods.  IntelliSense with Optional and Named parameters is very helpful.  Click on image to see larger size.

To show these features in action, start with a very simple class called person.

public class Person
{
  public string Name { get; set; }
  public int Age { get; set; }
  public string Phrase { get; set; }
  public string Email { get; set; }
  public string CellPhone { get; set; }
  public string HomePhone { get; set; }
  public string WorkPhone { get; set; }
}

Create a method that has optional parameters. Optional parameters are declared after all the required parameters. Optional parameters have a value specified in the declaration.

private Person GetPerson(string name, int age,
  string phrase = "I have no imagination", string email = null,
  string cellPhone = null, string homePhone = null, string workPhone = null)
{
  Person person = new Person()
  {
    Name = name,
    Age = age,
    Phrase = phrase,
    Email = email,
    CellPhone = cellPhone,
    HomePhone = homePhone,
    WorkPhone = workPhone
  };

  return person;
}

Each of these calls to GetPerson will compile but the “Mr. Spock” has a mistake. The phone number will be stored in the class Email property.  Sgt. Pepper shows how to use all named parameters.  By specifying the names, the user can pass the parameters in any order.

private List<Person> GetPeople()
{
  List<Person> people = new List<Person>()
  {
    GetPerson("Dave Jones", 45),
    GetPerson("Mr. Spock", 72, "Live Long and Prosper", "907 555-1212"),
    GetPerson("Correct Spock", 35, phrase: "Live Long and Prosper", cellPhone: "907 555-1212"),
    GetPerson("Johnny Quest", 13, phrase: "I Live for Adventure", workPhone: "202 555-1212"),
    GetPerson(homePhone: "213 555-1212", phrase: "I follow the beat of a different drummer", age: 64, name: "Sgt. Pepper"),
  };

  return people;
}

Tags:

2 Comments on Duck, Duck, … Goose

  1. Alex Essilfie says:

    It seems VB was good at something after all.
    I learned to program in C# some time ago and the thing I missed most was the Optional and Named Parameters.

    Good to know C# 4.0 now has it.

  2. I still like the with statement in VB. I used the with statement in Delphi but VB’s is better.

Leave a Reply


*