Friday, March 06, 2009

Passing Reference Variable using Pass-by-Value

This is bit of going back to school.But at times, it's nice to revisit old classes once in a while.

Pass-By-Value and and Pass-By-Ref is something we learnt when we all started coding. But these are some very basics which we often tend to overlook. I recently was talking to a friend of mine who was passing a KeyPressEventArgs object to a Method by value. We for a longer part, overlooked the basics of programming and kept wondering why the value of property "Handled" was changed , despite the object being passed as "pass-by-value".

But that’s exactly how it should be. The value ought to be changed because we are passing a reference variable by value. That's the quintessential behavior. Lemme put it up in an example.

private void ArrayChange(int []G)
{
G[0]= 3434;
}

private void MyFunction()
{
int []arr = new int[]{3,4};
ArrayChange(arr);
Console.WriteLine(arr[0]);
}

The output of this would be 3434 and NOT 3. This is because even though the array is being passed as Value, being the reference variable, it is the reference to array that gets passed and not the entire array as such.

This is exactly what happened in my case. KeyPressEventArgs being a reference variable reacted in the same way it has been designed to.

Well, rather to look our self as stupid, optimistically I would prefer to believe that such goof-ups would occur when one started looking beyond the basics. This is also where the KISS ( Keep It Simple Stupid) principle comes along.

As programmer's we often think too many complicated solutions for a very simple problem. Probably, it is quite a good idea to go back to school and get our basics refreshed.That would encourage us to put the solutions really simple and follow the KISS principle.