Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#/XNA extensions setting instance properties

Tags:

c#

vector

xna

I'm making an extension to the Vector2 class. In my main code, I can say

Vector2 v=new Vector2();
v.X=2;

But in my extension, I can't.

public static void SetToThree(this Vector2 vector)
{
    vector.X=3;       
}

v.SetToThree() doesn't change v. When I go line by line through the code, in the extension vector's X direction is changed to 3, but after the extension is finished, and the main code is continued, v hasn't changed at all. Is there any way for the extension method SetToThree to change v's value?

like image 759
AMWJ Avatar asked Apr 18 '26 10:04

AMWJ


1 Answers

Even though it looks like an instance method, it operates like a static method - so arg0 (this) is not ref - it is passed-by-value, hence you are mutating a copy of the struct. Since you can't use ref on the first argument of an extension method, you would have to return it instead:

public static Vector2 SetToThree(this Vector2 vector)
{
    vector.X=3;
    return vector;
}

and use:

v = v.SetToThree();

So possibly not worth it...

like image 179
Marc Gravell Avatar answered Apr 20 '26 18:04

Marc Gravell



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!