Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between referencing a value using a pointer and a ref keyword

Tags:

c#

unsafe

I have the following code:

class Program
{
    private unsafe static void SquarePtrParam(int* input)
    {
        *input *= *input;
    }

    private static void SquareRefParam(ref int input)
    {
        input *= input;
    }

    private unsafe static void Main()
    {
        int value = 10;
        SquarePtrParam(&value);
        Console.WriteLine(value);

        int value2 = 10;
        SquareRefParam(ref value2);
        Console.WriteLine(value2);

        //output 100, 100
        Console.ReadKey();
    }
}

What's the difference between passing a pointer and a ref keyword as a parameter in the method?

like image 606
Wallstrider Avatar asked Mar 21 '14 00:03

Wallstrider


1 Answers

The ref keyword acts like a pointer, but is insulated from changes to the object's actual location in memory. A pointer is a specific location in memory. For garbage-collected objects, this pointer may change, but not if you use the fixed statement to prevent it.

You should change this:

SquarePtrParam(&value);

to this:

fixed (int* pValue = &value)
{
    SquarePtrParam(pValue);
}

to ensure the pointer continues to point to the int data you expect.

http://msdn.microsoft.com/en-us/library/f58wzh21.aspx

like image 141
NathanAldenSr Avatar answered Sep 18 '22 12:09

NathanAldenSr