CodingYoshi wrote:
However, I also know that all objects are passed by reference.
That is not correct. By default, objects references are passed by value. Do not confuse variable data types (value types vs. reference types) with argument passing mechanisms (pass-by-value vs pass-by-reference). For example, arrays are reference types. When you create an array, a block of memory is allocated and your array variable contains a "reference" the to the memory area (typically a four-byte address). For example: In Visual Basic:
Dim values(10) As Integer
In C#:
int[] values = new int[10];
The variable, values, contains a reference to a block of ten integers. If you pass your array to a method as an argument, the reference to the array is passed by value (important). You can modify the elements of the underlying array but you cannot assign a new array to it. To illustrate what I am talking about, take a look at this C# code:
using System;
class Program
{
static void Main()
{
int[] values = { 1, 2, 3 };
TestMethod(values);
Console.WriteLine("{0}, {1}, {2}", values[0], values[1], values[2]);
}
static void TestMethod(int\[\] values)
{
int\[\] newArray = new int\[\] { 4, 5, 6 };
values = newArray;
}
}
This code will print "1, 2, 3". Why? First, an array containing { 1, 2, 3 } is created. The TestMethod() creates a new array with { 4, 5, 6 } and attempts to point your array reference to it. But when TestMethod() returns, the reference is not changed because the reference was passed by value. However, you can change the underlying data pointed to by the reference. If TestMethod() did this:
static void TestMethod(int[] values)
{
values[0] = 4;
values[1] = 5;
values[2] = 6;
}
... the values would be changed (i.e., it prints "4, 5, 6") because you passed a reference to the data contained in values, which TestMethod() is free to change.
CodingYoshi wrote:
when arguments are passed byVal it hinders performance since a copy needs to be made
Nah. Performance differences are usually insignificant. Maybe if you need to pass really large value types (like large structures) and you really need to t