Monday, July 9, 2007

Passing Parameters

  • Value Type Parameters
    Passing a value-type variable to a method means passing a copy of the variable to the method. Any changes to the parameter that take place inside the method have no affect on the original data stored in the variable. If you want the called method to change the value of the parameter, you have to pass it by reference, using the ref or out keyword.

    A common example of changing the values of the passed parameters is the Swap method, where you pass two variables, x and y, and have the method swap their contents. You must pass the parameters to the Swap method by reference; otherwise, you will be dealing with a local copy of the parameters inside the method.

    Passing Value Types by Value
    Passing value types by reference

  • Reference Type Parameters
    A variable of a reference type does not contain its data directly; it contains a reference to its data. When you pass a reference-type parameter by value, it is possible to change the data pointed to by the reference, such as the value of a class member. However, you cannot change the value of the reference itself; that is, you cannot use the same reference to allocate memory for a new class and have it persist outside the block. Pass the parameter using the ref (or out) keyword to do that.

    Swapping strings is a good example of passing reference-type parameters by reference.

    Passing reference types by value
    Passing reference types by reference

No comments: