Sunday, June 13, 2004 - Posts

.NET Parameter Passing

A topic that has been covered on many occasions, yet many developers I come into contact with still fail to grasp is that of .NET parameter passing semantics. I thought I would add to the pile of explanations my own attempt at explaining these intricacies.

Before I get into actual argument passing I want to define a few terms. First of all I want to briefly define reference types and value types. For the purposes of this description I will take a slightly non-standard approach to thier definition and define them in terms of components. Value types are instances that contain thier data, while references type instances hold a reference to the data which is located else where. In simple terms, and instance of a value type has only one component and that is the data held by the instance, while an instance of a reference type has two components, the reference and the data being referenced.

The .NET environment allows the developer to pass parameters in one of two ways, either by value or by reference. In VB.NET and C# the default is pass by value. When a value type is passed by value a new instance of the value type is created which contains a copy of the data contained in the original instance. Each instance can now be manipulated independently from the other.

In contrast, when a reference type is passed by value the called function receives a copy of the reference component of the reference type. Therefore when a function is passed a reference by value, there are at least two references in existence to the same piece of data, namely the original reference and the newly created reference, conversely there is still only one instance of the data that is being referenced.

That covers passing of value types and reference types by value. Now we can look at passing these types using the by reference semantic. Passing data by reference implies that the data itself is not passed, but a reference is passed. This allows the data to be manipulated through the reference rather than manipulating an independent local copy of the data.

When a value type is passed by reference, a reference is created to the data contained in the value type and this reference is then passed to the function. The end result is that we now have only one instance of the value type and the function receives a reference to this instance.

When passing a reference type by reference a new reference is created that references the reference type, this new reference is then passed in to the function which can now manipulate both the original reference and the data being referenced.

Trying to explain this without a board and marker and some of the usual props that I use is quite a challenge and I fully understand why so many developers struggle to grasp these concepts. I only hope that this attempt at a simplified explanation does not add to the confusion.