About Me

Hello, I'm an eclectic software professional working with enterprise software at SAP. This blog only contains my personal views, thoughts and opinions. It is not endorsed by SAP nor does it constitute any official communication of SAP.

Saturday, August 8, 2009

Optional Parameters and Method Overloads

The ability to declare optional parameters is another feature that will be introduced in C# 4.0. A natural complement to method overloads, it generally helps code to be more concise. Until now, method overloads have been used for the awkward responsibility of creating default values for what otherwise would be much better expressed as optional parameters. Many overloads have been created for which the sole responsibility is to call another overload with some default values for some parameters.

public CreditScore CheckCredit() {
  return CheckCredit(false, true);
public CreditScore CheckCredit(bool useHistoricalData) {
  return CheckCredit(useHistoricalData, true);
public CreditScore CheckCredit(
  bool useHistoricalData, bool useStrongHeuristics) {
  // do the heavy-lifting ...

For this style of method, optional parameters let you create just one method, with default values set on its signature.

public CreditScore CheckCredit(
  bool useHistoricalData = false, 
  bool useStrongHeuristics = true) {
  // ...

The key to make a parameter optional is to provide it with a default value. This code is less verbose and easier to maintain than the one with the overloads. The caller can omit any optional parameters and their default value will be what the method ultimately receives. This makes a lot of sense coupled with named parameters.

var creditScore = customer.CheckCredit(
  useStrongHeuristics: false);

Method overloads still have their place though. Normally when different versions of a method don't share code or when one must do some processing before or after calling another method, you'll still want to overload them. A good rule of thumb is if two methods have mutually exclusive sub-sets of parameters, they should be modeled as overloads.

public void SendSurvey(IList<Customer> customers, int surveyKey) { 
  // will loop and call the other one

public void SendSurvey(Customer customer, int surveyKey) { 

No comments:

Post a Comment