Search code examples
c#cpointersref

C# - Ref type comparison to pointers confusion?


I am reading Jeffrey Richters CLR via C#, and in it he says with ref parameters the reference itself is passed by value. This makes sense to me and seems analagous to pointers.

i.e. in C if I pass a pointer into a function and then assign the pointer via malloc it changes the pointer to point to the new memory location, however I know since the pointer itself is a copy it doesn't reassign the original pointer that was passed into the function. In order to accomplish change to the pointer outside the function I have to use a double pointer.

However, in C#:

void Swap(ref Object a, ref Object b)
{
    Object t = b;
    b = a;
    a =t ;
}

works. This indicates to me that references aren't by value. In analogy to the malloc above, I am assuming I could pass an object by reference and assign it a new object and the reassignment would persist outside the function.

Can someone clearup my confusion?


Solution

  • Without the ref keyword, an object's reference is passed by value.

    With the ref keyword, a reference to an object's reference is passed by value.

    [it's just that the compiler is hiding the fact that making the assignment to a parameter passed by explicit ref is changing the pointer]