The Ever Growing Myth of Passing Objects


Last month, one of my colleagues posed me an intriguing question on passing reference types by “ref”. I am writing this blog post, to share my explanation to a larger set of audience. I have coined the following analogy, to explain the concept of passing reference types.

Think that, you are playing with a kite (object) attached to a thread (pointer), and one of your friends also wants to play with the same.

Pass By Value
You attach an additional thread to the same kite (object), hand it over to your friend and both of you are now playing with the same kite. After a while your friend got bored, detached his thread, and attached it to a new kite (a new object). But, you won’t get affected as your thread is still tied to the old kite.

Pass By Reference
You hand over one end of the same thread to your friend and both of you are now again playing with the same kite. Again, after a while your friend, got bored of the old kite, detached the thread, and attached it to a new kite. But this time, you will also get affected as both of you are now sharing the same thread.

Against popular misconception, objects are not passed at all, only their addresses which are value types are passed between the methods. So, the concept is not anymore different from passing value types. By passing an object’s address by value, you have two pointers for the same object, so you can control its internal state with any pointer. Whereas passing an object ‘s address by reference, you share the same pointer, so you not only can change its internal state, but also can point to a new object.

Comments

Popular posts from this blog

Chrome Extension - Tab Keeper

The life of a software developer, who can never write a program as efficiently as his manager wants it, for the first time.

The Never Ending War of Software Constructors and Software Destructors