public Class MyClass
{
public int a;
public int b;
}
Passed by reference means that a reference to the parameter is passed to the method, and any changes to the parameter will be reflected outside of the method when it returns, because the reference is to the exact same object in memory. Let's use the same example as before, but we'll "wrap" the int
s in a class first.
MyClass instanceOfMyClass = new MyClass();
instanceOfMyClass.a = 5;
instanceOfMyClass.b = 6;
AddNumbers(instanceOfMyClass);
public AddNumbers(MyClass sample)
{
int z = sample.a + sample.b; // z becomes 11
sample.a = sample.a + 5; // now we changed a to be 10
z = sample.a + sample.b; // now z becomes 16
}
This time, when we changed sample.a
to 10
, the value of instanceOfMyClass.a
also changes, because it was passed by reference. Passed by reference means that a reference (also sometimes called a pointer) to the object was passed into the method, instead of a copy of the object itself.
Remember, Reference types live on the heap, and are passed by reference.