Recently, I met a problem that how to change "int" value when using the extension method, don't allow use keyword "ref" or "out":
static void Main(string[] args)
{
var a = 5;
var b = 6;
a.Swap(b);
Console.WriteLine("a={0},b={1}", a, b);
Console.ReadKey();
}
I want to implement the Swap method(exchange variable a and variable b) and final output like this:
a = 6,b = 5
Swap method needs to exchange variable a and variable b, The issue is assigned by my teacher.
My answer is :
unsafe static void Swap(this int a, int b)
{
int* pb = &b;
pb += 7;
int* pa = &a;
pa += 8;
int temp = *pa;
*pa = *pb;
*pb = temp;
}
But my teacher said it not good enough. Because the 7 and 8 will be affected by the C# compiler.
I really didn't know how to implements Swap method. I think the integer will be passed by value when passing into Swap, and can't change it unless finding out its original address.
Did I misunderstand something? Your thought would be appreciated.