ref parameters

G

Gigs_

namespace WindowByRef
{
class Window
{
public Window(int x, int y)
{
this.x = x;
this.y = y;
}

protected int x;
protected int y;

public void Move(int x, int y)
{
this.x = x;
this.y = y;
}

public void ChangePos(ref int x, ref int y)
{
this.x += x;;
this.y += y;

x = this.x;
y = this.y;
}
}

class TestWindowByRef
{
public static void Main()
{
Window wnd = new Window(5, 5);
int x = 5;
int y = 5;

wnd.ChangePos(ref x, ref y);
Console.WriteLine("{0}, {1}", x, y);

x = -1; // i would expect that x here is 10 -1 not 5 -1 but its 5 -1 or x =
this.x; in ChangePos not affect outside
y = -1;
wnd.ChangePos(ref x, ref y);
Console.WriteLine("{0}, {1}", x, y);
}
}
}


can someone just explain me this

thx
 
J

Jon Skeet [C# MVP]

can someone just explain me this

It's not at all clear why you'd expect it to be 10-1 - it will be 10
before the assignment, and -1 after the assignment. When I run your
code, it outputs;
10, 10
9, 9

which is just what I'd expect. What are you seeing, and what would you
expect to see?

Jon
 
M

Marc Gravell

Can you clarify what behavior you were expecting?

I'll treat x & y the same, since you do the same to both;

You start at 5

You call ChangePos passing 5, which moves the window to 10, and update
the ref-variable to this value: 10

Output 10

You set the variable to -1

You call ChangePos passing -1, which moves the window to 9, and update
the ref-variable to this value: 9

Output 9

---

Is this not what you are seeing?


Marc
 
G

Gigs_

Jon said:
It's not at all clear why you'd expect it to be 10-1 - it will be 10
before the assignment, and -1 after the assignment. When I run your
code, it outputs;
10, 10
9, 9

which is just what I'd expect. What are you seeing, and what would you
expect to see?

Jon
sorry for your time. maybe my brain didn't work last few hours
;-)
 
G

Gigs_

Marc said:
Can you clarify what behavior you were expecting?

I'll treat x & y the same, since you do the same to both;

You start at 5

You call ChangePos passing 5, which moves the window to 10, and update
the ref-variable to this value: 10

Output 10

You set the variable to -1

You call ChangePos passing -1, which moves the window to 9, and update
the ref-variable to this value: 9

Output 9

---

Is this not what you are seeing?


Marc
thx i figure it. i was looking at x=-1 but i sow x-=1
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top