reference type  
Author Message
nativecpp





PostPosted: Visual C# Language, reference type Top

Hi all,

I was reading the following:

"If you specify that a reference type should be passed by value, a copy of the reference is made and the copy is passed".

How do you pass a refernece as value in C# I thought, for example, string is a reference class, all I need to do is just call Foo(str) and it is passed by reference and there is no need for ref. Am I missing something.

Thanks



Visual C#1  
 
 
Dennis Stone - MSFT





PostPosted: Visual C# Language, reference type Top

You pass a reference type by value if you don't use the ref keyword.  But that doesn't necessarily mean you can't change the value of what the reference type is referencing, it just means you can't change the value of the reference itself (you can change the data it points to, but not which data it points to).

For example, if you have a Class named Data with 3 fields (exposed by properties) named Field1, Field2, and Field3, and you pass it like this:

ChangeData(myDataObject);

This function can change the values of Field1, 2, and 3 and they will persist.  What won't work in this function is something like: myDataObject = new Data();  It will appear to work but you'll really only be changing the local copy of the myDataObject reference.

In this case you've changed the value of the reference itself, which is passed by value.  So when you leave this method your myDataObject will still point to the same thing it pointed to before you called the method.

This is why you can't pass a String by value and change it's contents.  When you change the data a string references you actually destroy the old reference and create a new one.  When you change the value of the reference itself its only changing the copy of the value that is local to the method.

For more detail there's an msdn article you can take a look at here: http://msdn2.microsoft.com/en-us/library/s6938f28.aspx that covers this topic.

Hope that helps,

Dennis



 
 
nativecpp





PostPosted: Visual C# Language, reference type Top

Thanks.
 
 
nativecpp





PostPosted: Visual C# Language, reference type Top

Actually the statement I quoted has another statement before that:

It is important to know that reference types are always passed by reference. If you specify that a reference type should be passed by value, a copy of the reference is made and the copy is passed

If the bold statement is true, would that be correct that there is no need to add ref and therefore I could modify the reference to point to some other objects. In addition, "If you specify that a reference type should be passed by value", that would imply that you need to specify some keyword in order to make a reference type passed by value

Thanks