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?
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With