What is different from "Pass by value" and "Pass by reference using C #

Possible duplicate:
What is the difference between a parameter passed by reference or a passed value?

It’s hard for me to understand the difference between passing by value and passing by reference. Can someone provide a C # example illustrating the difference?

+6
c #
source share
4 answers

In general, read my article on parameter passing .

Main idea:

If the argument is passed by reference, then changes in the parameter value inside the method also affect the argument.

The subtle part is that if the parameter is a reference type, then do:

someParameter.SomeProperty = "New Value"; 

does not change the value of the parameter. The parameter is just a reference, and what is related to the parameter does not change above, but only the data inside the object. Here is an example of a true change in a parameter value:

 someParameter = new ParameterType(); 

Now for examples:

A simple example: passing int by reference or by value

 class Test { static void Main() { int i = 10; PassByRef(ref i); // Now i is 20 PassByValue(i); // i is *still* 20 } static void PassByRef(ref int x) { x = 20; } static void PassByValue(int x) { x = 50; } } 

A more complex example: using reference types

 class Test { static void Main() { StringBuilder builder = new StringBuilder(); PassByRef(ref builder); // builder now refers to the StringBuilder // constructed in PassByRef PassByValueChangeContents(builder); // builder still refers to the same StringBuilder // but then contents has changed PassByValueChangeParameter(builder); // builder still refers to the same StringBuilder, // not the new one created in PassByValueChangeParameter } static void PassByRef(ref StringBuilder x) { x = new StringBuilder("Created in PassByRef"); } static void PassByValueChangeContents(StringBuilder x) { x.Append(" ... and changed in PassByValueChangeContents"); } static void PassByValueChangeParameter(StringBuilder x) { // This new object won't be "seen" by the caller x = new StringBuilder("Created in PassByValueChangeParameter"); } } 
+16
source share

Passing by value means that a copy of the argument is being passed. Changes to this copy do not change the original.

Passing by reference means that the link to the original is transmitted and changes in the link affect the original.

This does not apply to C #, it exists in many languages.

+5
source share

Digest:

Passing by reference is used when you expect a function / method to change your variable.

Pass by value when you do not.

0
source share

All Articles