Home > Articles > Programming > Windows Programming

  • Print
  • + Share This
From the author of

Method Overloading

.NET supports creating overloaded methods and properties to provide different methods with the same name that perform the same basic function. The power overloading makes it important that you use it in a consistent way.

As with constructors, you should use a consistent ordering and naming pattern for the signatures, to expose increasing levels of detail for the method. When the class will be derived by other classes, you should make only the most complete method (the one with the most arguments) able to be overridden using the keywords virtual in C# and Overridable in VB .NET. If the method needs to be passed a variable number of arguments, you can define n signatures that take increasing numbers of arguments and then create a signature that accepts an array of values for numbers of arguments greater than n. An alternative approach is to simply define a single method that accepts a variable number of arguments using the keywords params in C# and ParamArray in VB .NET. This is particularly effective for methods that need to accept arguments to formulate queries sent to a database through ADO.NET.

In many cases, methods that are overloaded eventually expose parameters that map to properties that change the default behavior of the class. For example, the following class definition in C# exposes a disableEvents parameter in its constructor:

public class Registration
{
  private Boolean _disableEvents = true;

  public Boolean EnableEvents
  {
    get { return _disableEvents; }
    set { _disableEvents = value; }
  }

  public Registration(Boolean disableEvents)
  {
    // implementation
    this.EnableEvents = disableEvents;
  }

  public Registration()
  {
    // assumes disableEvents is true
  }
}

The important point to note in the previous code's Registrations class is that if the empty (default) constructor is used, the EnableEvents property will be defaulted to true because the private variable _disableEvents is set to true automatically. As a result, the constructor that accepts the parameter should use a name that indicates a change from the default state—in this case, disableEvents. This makes it clearer that the constructor can be used to affect the default behavior of the class.

  • + Share This
  • 🔖 Save To Your Account