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 notref– it is passed-by-value, hence you are mutating a copy of the struct. Since you can’t userefon the first argument of an extension method, you would have toreturnit instead:and use:
So possibly not worth it…