开发者

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 fun开发者_C百科ction.

Can someone clearup my confusion?


You have it slightly off. With reference types, the references are passed by value. Passing a ref parameter is different. In

private void Frob(Foo foo) // Foo is a class
{

}

A copy of the reference to the object of type Foo at the call site is passed into the method Frob. This copy of the reference is passed by value. This reference and the reference at the call site point to the same object in memory and will continue doing so until one of them is pointed at some other object in memory. For example, if inside this method, we write

foo = someOtherFoo;

Then the parameter is no longer referring to the same object as the object at the call site. The call site reference is unchanged.

Now consider if we introduce the ref keyword.

private void Frob(ref Foo foo)
{
    foo = someOtherFoo;
}

In this situation, foo is an alias of the variable at the call site. These variables are not merely pointing at the same object in memory, it's as if they are the same variable! As a result, pointing foo to someOtherFoo is not only going to change foo inside this method, this change will also be reflected at the call site.


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]


When called this passes the original pointer value (the reference)

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

This passes a copy of the original pointer:

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

Both will point to the same object but changing the second won't be reflected in a greater scope that this method...

I do not exactly get the question though...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜