Reputation:
Whats going on here? Why isn't the = working? It's not a value type so it should be passing by reference right?
void func()
{
Vector2 a = new Vector2(1, 0);
equal(a);
// a is now (1, 0) not (0, 0)
}
void equal(Vector2 a)
{
a = new Vector2(0, 0);
}
Upvotes: 2
Views: 3276
Reputation: 4869
Because the reference to a is passed as value and not as reference, so you are modifying a ' local' a.
correct would be:
void equal ( ref Vector2 a)
Upvotes: 3
Reputation: 1894
A reference type can be passes by value or by reference. The default is to pass by value which is what your code sample does.
When a reference type is passed by value, you can modify the state of the object but you cannot change the reference itself so it would refer to a new object. To do that you must pass by reference.
void equal(ref Vector2 a)
{
a = new Vector2(0, 0);
}
Here is a direct link to the part of my online .NET training which illustrates all cases with animation and code samples: http://motti.me/cf
I hope this helps!
Motti
Upvotes: 0
Reputation: 63105
Vector2
is Struct
and struct type is a value type
not reference. use ref
keyword passing by reference
Upvotes: 1
Reputation: 61862
You're not passing by reference. To do that, you'll need to use the ref
keyword
void func()
{
Vector2 a = new Vector2(1, 0);
equal(ref a);
}
void equal(ref Vector2 a)
{
a = new Vector2(0, 0);
}
Upvotes: 2
Reputation: 499402
In order to change the reference you would need to pass by ref to ensure the reference changes.
void func()
{
Vector2 a = new Vector2(1, 0);
equal(ref a);
}
void equal(ref Vector2 a)
{
a = new Vector2(0, 0);
}
I suggest reading about Value Types and Reference Types and this.
Upvotes: 1
Reputation: 755587
C# passes arguments by value by default hence it's only assigning to a
within the equal
method. You need to use a ref
parameter here if you want pass by reference
void func()
{
Vector2 a = new Vector2(1, 0);
equal(ref a);
// a is now (0, 0) as expected
}
equal(ref Vector2 a)
{
a = new Vector2(0, 0);
}
Upvotes: 6
Reputation: 26633
A copy of the reference to a is being passed to the equal method. The code inside equal is changing the memory location pointed to by the copy. See http://msdn.microsoft.com/en-us/library/0f66670z(v=vs.71).aspx#vclrfpassingmethodparameters_example4 for details.
Just to be clear: The Vector2 object is not being copied, the variable a is being copied when it is passed to the method.
Upvotes: 0
Reputation: 57603
You should try:
void func()
{
Vector2 a = new Vector2(1, 0);
equal(ref a);
}
void equal(ref Vector2 a)
{
a = new Vector2(0, 0);
}
Upvotes: 0