What is the difference between passing variables by reference or by value?
Im thinking that when you pass a variable by reference, you simply make a reference name for it in the parameters of the method that refers back to the variable that was "passed" to the method in the calling parameters. With this method you cannot actually change the contents of the passed variable.
With passing by value, you create a copy of the variable that is "re-instantiated" in the parameters of the method and can be modified and what not, just as if it were a variable that was declared in the method itself but it comes into the method with a preloaded value. Using this method, you CAN change the value of the passed variable.
How about it? Did I answer my own question? lol
Loading
Posted Jul 3, 2007, 1:07 PM
AlanPosted Jul 3, 2007, 1:03 PM
If you pass an object of a value type (such as an int, double etc) by value, then a copy of that value is made and assigned to the parameter. The value of the parameter can then be changed by the method without affecting the value of the original object that was passed in as an argument.
If you pass an object of a reference type (such as string, object etc) by value, then a copy is made of the reference (i.e. a pointer to where the object is stored) and assigned to the parameter. The 'state' of that object (i.e. its fields) can then be changed by the method and these changes will be persisted to the object once the method returns.
If you pass an object of a value type by reference, then a managed pointer to where that object is stored is created and assigned to the parameter. Any changes to the value of this parameter made by the method will then be persisted to the object once the method returns.
Finally, if you pass an object of a reference type by reference, then a managed pointer to the reference is made (i.e a pointer to a pointer to where the object is stored) and assigned to the parameter. This means that not only can the state of the original object be changed but, by assigning a new object of the same type to the parameter, the variable passed in as an argument will now refer to that object rather than the original object when the method ends.
Simple, eh :)