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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With