- Home /
Something I don't fully understand about C# - the ref modifier
C# has a ref parameter which basically allows you to refer to a value passed on via a method. This can be useful for primary types such as int and string. However, is there any usage to use ref when passing instances of objects? They seem to be references by themselves in C# (just like in Java, JS and AS3)
Considder the following code:
public class NewBehaviourScript : MonoBehaviour
{
void Start ()
{
TestObject testObject = new TestObject();
testObject.setName("Foobar");
Debug.Log(testObject.getName()); // prints Foobar
changeTheName(testObject);
Debug.Log(testObject.getName()); // prints FoobarChanged
}
public void changeTheName(TestObject testObjectViaMethod)
{
testObjectViaMethod.setName("FoobarChanged");
}
}
As expected this does modify testObject, therefore doesn't make a local copy/saves memory allocation.
But I'm still wondering whether there is any use to use ref with instances of objects :)
Answer by Jesse Anders · Feb 01, 2011 at 12:05 PM
You've probably already gotten the answers you need (the article linked in the other answer is pretty comprehensive, I think), but yes, you can pass an object reference by reference, and it's conceptually distinct from passing the object reference itself.
If you've ever programmed in C or C++, a reference to a reference in C# is somewhat similar to a pointer to a pointer ('**') in C or C++. In other words, it allows you to modify the value of the reference itself, rather than the object to which the reference refers.
As I understand it at least, all function arguments are passed by value in C# unless otherwise specified (e.g. using the 'ref' keyword). When you pass a reference to an object of a class type, you're actually passing a reference to that object by value.
You would pass an object reference by reference if you actually wanted to change the value of the original reference (yes, it's a little confusing). Note that both 'ref' and 'out' can be used for this, although the two keywords work in somewhat different ways.