Reputation:
I have difficulty understanding the difference between passing by value and passing by reference. Can someone provide a C# example illustrating the difference?
Upvotes: 7
Views: 11060
Reputation: 1500515
In general, read my article about parameter passing.
The basic idea is:
If the argument is passed by reference, then changes to the parameter value within the method will affect the argument as well.
The subtle part is that if the parameter is a reference type, then doing:
someParameter.SomeProperty = "New Value";
isn't changing the value of the parameter. The parameter is just a reference, and the above doesn't change what the parameter refers to, just the data within the object. Here's an example of genuinely changing the parameter's value:
someParameter = new ParameterType();
Now for examples:
Simple example: passing an int by ref 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;
}
}
More complicated 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");
}
}
Upvotes: 17
Reputation: 2076
The digest is:
Passing by reference is used when you expect the function/method to modify your variable.
Passing by value when you don't.
Upvotes: 0
Reputation: 881423
Passing by value means a copy of an argument is passed. Changes to that copy do not change the original.
Passing by reference means a reference to the original is passed and changes to the reference affect the original.
This is not specific to C#, it exists in many languages.
Upvotes: 5