-1

I am just trying to swap the address in the pointer. You know just try. SO I get my pathetic code:

unsafe class Test
{
    static void Main()
    {
        int a = 1; int b = 2;
        int* x = &a, y = &b;
        Console.WriteLine($"{*x} and {*y}");
        Swap(out x, out y);
        Console.WriteLine($"{*x} and {*y}");
    }

    static void Swap(out int* a, out int* b)
    {
        long x = (long)a;
        long y = (long)b;
        x ^= y ^= x ^= y;
        a = (int*)x; b = (int*)y;
    }
}

Terrible error:

Error    CS0269    Use of unassigned out parameter 'a'    ConsoleApp1
Error    CS0269    Use of unassigned out parameter 'b'    ConsoleApp1    

Why? Can't I using the keyword out to the pointer?

  • 2
    You likely want `ref` there, not `out`. – Amadan Apr 03 '23 at 03:50
  • `out` means (among other things) "I will not read from `a` before I write to it." But you are reading from it at the start of the function. As noted by another comment, it looks like you want `ref` which allows you to read the old value. – Raymond Chen Apr 03 '23 at 03:51
  • The default behaviour for parameters is pass a value in only. `out` means pass a value out only and `ref` means in and out. – jmcilhinney Apr 03 '23 at 03:53
  • Note that it's relativly close to the code explaining CS0269 https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-messages/cs0269 – Drag and Drop Apr 03 '23 at 06:22

1 Answers1

4

The out-keyword- other as the ref-keyword, won't use the value you provide to the called function at all. It just assigns the value regardless of if you provided a value or not. So the following two calls are pretty much the same and will produce the exact same value for i after executing myFunction:

int i = 0;
myFunction(out i);

int i = 1000;
myFunction(out i);

So in this line long x = (long)a; a won't have a value at all, which is why you get that compiler-error. In order to just change the value passed to the function, you need the ref-keyword:

static void Swap(ref int* a, ref int* b)
{
    long x = (long)a; // a now has the value provided to the function
}
MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111