Passing objects by reference/value in C#

Many developers’ knowledge about passing object as parameters can be summed up with the following “In c# object parameters are always being passed by reference, if i will pass some object to another code, the same object will be in context”. While this knowledge is sufficient for most of the cases, it might cause bugs in a few. Lets take a look at some code snippet:

//some mediator code, WIN forms code behind
tennisCourt availableCourt = getAvailableCourt();
someGUIControl.showTennisCourt(availableCourt)

//now some event raised, other court is available
tennisCourt availableCourt = getAlternateCourt();
updateGUI()

Will the GUI present the new available court? NO. Why is that? After all we have passed the availableCourt variable “by reference” so why will the GUI component not have the updated tennisCourt?

That is because when you simply pass object to some other component, it is by default being passed by value. When some code (e.g. function) receives object ,by default, it will dupliacte/copy the parameter. Not the object itself will be duplicated but the pointer which points to that object will be duplicated.

//The receiving code, some GUI component
public void showTennisCourt(tennisCourt courtToShow){}

This function will create it’s own, local-scoped variable, which is pointing to the same tennisCourt as the code who called it. As long as the two codes (1. The windows form , 2. The receiving¬† GUI component)¬† are referencing the same tennisCourt – everything goes well. The problems start when the calling code is creating a new tennisCourt:

//now some event raises, other court is available
tennisCourt availableCourt = getAlternateCourt();
updateGUI()

After this lines are executed, the variable availableCourt is referencing a whole new object with another memory address and it’s a totally different object from the one the GUI component had received. So when you ask to update the GUI, it still has the old object and nothing is changed there. Let’s illustrate this with a diagram:

 
If you want two running codes to refer to the same pointer (same reference variable) use ref keyword (just to illustrate the technique, apply only when suitable) , this will promise you that the two codes are not only refering to the same object but also using the same pointer (that points to that object):
public void showTennisCourt(ref tennisCourt courtToShow){}

  • Thank you very much Yoni.

© 2021 Yoni Goldberg. All rights reserved.