Jump to content
  • Advertisement
Sign in to follow this  
quasar3d

[.net] Swapping two variables

This topic is 4951 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I just started with C#, and I need two swap to variables. I can create my own swap function, but I'm sure there must be one in the standard library already, but I couldn't find it. Does .net have a swap function, or do I have to make one myself? [Edited by - quasar3d on December 11, 2004 10:43:57 AM]

Share this post


Link to post
Share on other sites
Advertisement
I tried to make my own swap function, but it doesn't work.

this is the function:

public static void Swap(ref object a, ref object b)
{
object swap = a;
a = b;
b = swap;
}


and then I try to call it like this:

App.Swap(ref pen1,ref pen2);

but it doesn't work, it only works with objects, but not with other classes, like Pen in this case. Pen is derived from object though. I get this error:
Argument '2': cannot convert from 'ref System.Drawing.Pen' to 'ref object'

Share this post


Link to post
Share on other sites
Quote:
it only works with objects, but not with other classes, like Pen in this case. Pen is derived from object though. I get this error:
Argument '2': cannot convert from 'ref System.Drawing.Pen' to 'ref object'


That's right. ref or out parameters in methods must exactly match the types in their declarations, so there isn't a generic solution to your problem in the 1.0 or 1.1 versions of the Framework and C# compiler. You'll therefore need to make a specific Swap method for each object type you want to swap.

Thankfully, version 2.0 of the Framework makes this much easier, because it has generics. If you're using that version, then what you want is:


void Swap<T>(ref T item1, ref T item2)
{
T swap = item1;
item1 = item2;
item2 = swap;
}


Share this post


Link to post
Share on other sites
The static methods
System.Threading.Interlocked.Exchange( ... );
swap two variables in a threadsafe manner.

However, the limitation of the ref parameters still apply...

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!