Hi I\'m trying to do a simple swap of two objects.My code is
void Main()
{
object First = 5;
object Second = 10;
Swap(First, Second);
//If I display res
You're passing the reference to the objects by value (pass by value is the default in C#).
Instead, you need to pass the objects to the function by reference (using the ref keyword).
private static void Swap(ref object first, ref object second)
{
object temp = first;
first = second;
second = temp;
}
void Main()
{
object first = 5;
object second = 10;
Swap(ref first, ref second);
}
Of course, if you're using C# 2.0 or later, you would do better to define a generic version of this function that can accept parameters of any type, rather than the object type. For example:
private static void Swap(ref T first, ref T second)
{
T temp;
temp = first;
first = second;
second = temp;
}
Then you could also declare the variables with their proper type, int.