Passing Parameters By Ref In C#… WHAT?

|

I am not a huge .NET fan, but I am mature enough to overcome my personal likes and dislikes in a professional setting and use whatever is needed. I recently ran into a situation programming in C# that I needed to create a method that took it’s parameters by reference. Why would you want to do that? Well, a parameter passed by reference is… well a reference to the original memory location of the variable. This means that when you pass a parameter into a method by reference any changes made to the parameter within that method are preserved when the method goes out of scope. Ok, now we have that out of the way.

To create a method which takes a parameter by reference in C# you simply use the ref keyword in front of the parameter declaration. Easy! To illustrate this point I will use the standard swap method.

public void swap(ref int x, ref int y) {
  int temp = x;
  x = y;
  y = temp;
}

To call this function I would have initially done the following:

int x = 5;
int y = 10;
swap(x, y);

And I would be wrong! This would result in a compiler error(s) stating something like “Argument X must be passed with the 'ref' keyword“. You have to make the call as follows:

int x = 5;
int y = 10;
swap(ref x, ref y);

Surely you can’t mean… oh yeah. You must use the ref keyword when you call the method. In fact you cannot leave the ref keyword out of the method declaration either. You must use ref in both the method declaration and the calling statement. Well, that’s not so bad is it? I suppose not, but why force me to specify ref when I am calling the method. If it is in fact required in both places and will not compile otherwise, couldn’t they have just assumed that since I defined the method parameter as a pass by reference that every call to that method knows this as well?

In C++ this is exactly how it works! And you only use a single char to define a pass by reference parameter so there is even less code. The above sample in C++ would look something like:

void swap(int& x, int& y) {
  int temp = x;
  x = y;
  y = x;
}

That’s almost exactly the same. But when I call the method it just looks like this:

int x = 5;
int y = 10;
swap(x, y);

Just as I would expect it… much more intuitive. That is more like it!