Why with this code:
unsafe
{
for (int i = 0; i < 10; i++)
{
Double w = new Double();
Console.WriteLine((IntPtr)(&w));
}
}
i'm always getting the same number? How to create new variables in a loop ? With new addresses ?
The reason, why this is a problem for me is that I need to generate a random double number and then I'm using a pointer (which references to that double) in two objects. In one of the object I'm changing this value and I want it to change in that other object too :)
Logically, that's a new variable every time through the loop. But I hope that you would not expect a new variable to actually be allocated off the stack every time! What if the loop runs a million times? The compiler knows that it can re-use the storage, and it does.
If you want ten different addresses, make an array with ten elements, fix it in place, and take the address of each element.
It seems you want to share the reference to the value of the value type. So, it can be done by wrapping the value type into the reference type:
class Ref<T>
{
public T Value { get; set; }
}
Please also see the related question: C# - Good and flexible way to pass value types by reference?.
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