Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# pass by ref not working?

Tags:

c#

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);
}

2 Answers

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);
}
like image 66
JaredPar Avatar answered Jun 18 '26 05:06

JaredPar


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)
like image 38
Mario The Spoon Avatar answered Jun 18 '26 03:06

Mario The Spoon



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!