Evan Sevy
Evan Sevy

Reputation: 687

'ref' not working like I think it should

I have the following code which when looking at it while it's running shows that the initial 'myInt' and 'myFloat' do not change their values until the method call returns back. Shouldn't their values change each time they are altered within the called methods since they are passed as 'ref' each time?

class Tester
{
    public void Run()
    {
        int myInt = 42;
        float myFloat = 9.685f;
        Console.WriteLine("Before starting: \n value of myInt: {0} \n value of myFloat: {1}", myInt, myFloat);
        // pass the variables by reference
        Multiply( ref myInt, ref myFloat );
        Console.WriteLine("After finishing: \n value of myInt: {0} \n value of myFloat: {1}", myInt, myFloat);
     }
     private static void Multiply (ref int theInt, ref float theFloat)
     {
        theInt = theInt * 2;
        theFloat = theFloat *2;
        Divide( ref theInt, ref theFloat);
     }
     private static void Divide (ref int theInt, ref float theFloat)
     {
        theInt = theInt / 3;
        theFloat = theFloat / 3;
        Add(ref theInt, ref theFloat);
     }
     public static void Add(ref int theInt, ref float theFloat)
     {
        theInt = theInt + theInt;
        theFloat = theFloat + theFloat;
     }
     static void Main()
     {
        Tester t = new Tester();
        t.Run();
     }
}

Upvotes: 3

Views: 385

Answers (3)

user7116
user7116

Reputation: 64148

You placed a Watch on the expressions myInt and myFloat rather than the expressions theInt and theFloat, thus you no longer see their values. myInt and myFloat do not exist in the current scope.

The Watch Window uses expressions not variables

You can back up in the call stack to observe their values, or place a watch on all four of the expressions you care about.

Select the original method in your call stack to view their values

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1504182

EDIT: Okay, having seen the description in your comments...

If you put a breakpoint in (say) Add then your watch variables won't change unless you get them to be re-evaluated - which has to be done in the right stack from. When the breakpoint has been hit, go to the Call Stack view, double click on the "Run" method (which doesn't change where you've got to, just which stack frame you're looking at) and you'll see the values update.

Upvotes: 4

Kieren Johnstone
Kieren Johnstone

Reputation: 42023

It's a debugger anomaly, the values change right away, as per Jon's and jamietre's comments.

Upvotes: 1

Related Questions