views:

56

answers:

1

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?

+3  A: 

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...

Marc Gravell
Or, if possible, make Vector a Class (which should be passed-by-Reference) instead of a Struct (passed-by-value).
Andy Jacobs
@Andy - that is a common existing XNA type.
Marc Gravell