Fog Creek Software
Discussion Board




Welcome! and rules

Joel on Software

swap function in c#

this came up in an interview:

write a function to swap the value of two objects A and B.  The function definition supplied was:

  void swap(object a, object b)

I said you had to use ref parameters to do it.

Am I wrong? 

I'm not sure if they were just testing to see if I knew the difference between value/ref arguments, or if they were looking for something deeper that I might have missed.

   

Jason
Wednesday, April 13, 2005

I think that's impossible in C#.

Colm O'Connor
Wednesday, April 13, 2005

Yes, you would need to use ref parameters. I'm not sure what they were after. One would really need clarification on the phrase "swap values" to answer completely. What does that really mean?

You can see how the following code would work but not really solve any real problems since the "values" being swapped are just references. The objects themselves are not having their "values" swapped (Text, positions, etc.).

private void button1_Click(object sender, System.EventArgs e)
{
    object a = new Button();
    object b = new TextBox();

    this.swap(ref a,ref b);
}

private void swap(ref object a, ref object b)
{
    object c = a;
    a = b;
    b = c;
}

matt
Wednesday, April 13, 2005

The code runs and does swap the objects assigned to a and b.

Without using ref the compiler would make a copy of a and b and so swap() would swap the copies, leaving the originals unchanged. using ref passes a reference (effectively a pointer) to the original objects, and the trick is that the assignment in swap() silently dereferences them - equivalent to &a, &b in C++.

Still, not very useful to swap a button for a textbox.

Rich

Rich
Thursday, April 14, 2005

*  Recent Topics

*  Fog Creek Home