The following rules outline the usage guidelines for parameters:
  • Check for valid parameter arguments. Perform argument validation for every public or protected method and property set accessor. Throw meaningful exceptions to the developer for invalid parameter arguments. Use the System.ArgumentException Class, or a class derived from System.ArgumentException. The following example checks for valid parameter arguments and throws meaningful exceptions.

class SampleClass {
  public int Count {
    get {
    return count;
    }
    set {
      // Check for valid parameter.
      if ( count < 0 || count >= MaxValue ) {
        throw newArgumentOutOfRangeException ( Sys.GetString ( "InvalidArgument","value",count.ToString ( ) ) ); 
      }
    }
  }

  public void Select ( int start, int end ) {
    // Check for valid parameter.
    if ( start < 0 ) {
      throw new ArgumentException ( Sys.GetString ( "InvalidArgument", "start", start.ToString ( ) ) );
    }
    // Check for valid parameter.
    if ( end < start ) {
      throw new ArgumentException ( Sys.GetString ( "InvalidArgument", "end", end.ToString ( ) ) );
    }
  }
}

Note that the actual checking does not necessarily have to happen in the public or protected method itself. It could happen at a lower level in private routines. The main point is that the entire surface area that is exposed to the developer checks for valid arguments.
  • Make sure you fully understand the implications of passing parameters by value or by reference. Passing a parameter by value copies the value being passed and has no effect on the original value. The following method example passes parameters by value.
public void Add ( object value ) {

}
Passing a parameter by reference passes the storage location for the value. As a result, changes can be made to the value of the parameter. The following method example passes a parameter by value.
public static int Exchange ( ref int location, int value ) {

}
An output parameter represents the same storage location as the variable specifed as the argument in the method invocation. As a result, changes can be made only to the output parameter. The following method example passes an out parameter.
[DllImport ( "Kernel32.dll" )]
public static extern bool QueryPerformanceCounter ( out long value );

Last edited Jul 19, 2010 at 12:35 PM by camalot, version 1