Wednesday, January 2, 2008

ByVal vs ByRef (2)

  • Avoid defining methods that take arguments passed by reference
  • There is rarely the need to pass a reference type to a by-reference parameter because a by-value parameter still lets the method read and modify all the field and properties of the object
  • The only exception to this rule is when the method must be allowed to set the parameter to a null object reference or to make it point to a different object

There are four cases in total:

  • Passing value types by value: A copy of the value type is created and passed to the method. This exhibits no side effects because the callee cannot change any member of the original value type. (Cannot change anything)
  • Passing reference types by value: A copy of the pointer to the object is created and passed to the method. The method can use the parameter to access and change the fields and properties of the object. If the method changes the parameter (e.g. it assigns it a null value or makes it point to a different instance), the original object variable is not affected. (Can only change fields and properties)
  • Passing value types by reference: A pointer to the original value is passed to the method. When a value type argument is passed by reference, the code in the method can modify fields and properties in the value type. This case is mostly used in nonvoid/function methods when you want to return additional information to the caller or in COM interop scenarios. (Can only change fields and properties)
  • Passing reference types by reference: The address of the pointer to the object is passed to the method. The callee can change the object's fields and properties, plus all the changes to the pointer are reflected in the original object variable. If the method sets the argument to a null object reference, the original object variable is set to null as well. (Can change anything)

Practical Guidelines and Best Practices for Microsoft Visual Basic and Visual C# Developers

blog comments powered by Disqus