Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why for loop is creating variable with the same address?

Tags:

c#

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 :)

like image 254
Benas Radzevicius Avatar asked Jan 17 '26 21:01

Benas Radzevicius


2 Answers

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.

like image 196
Eric Lippert Avatar answered Jan 19 '26 19:01

Eric Lippert


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?.

like image 42
Sergey Vyacheslavovich Brunov Avatar answered Jan 19 '26 19:01

Sergey Vyacheslavovich Brunov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!