A Class that hold a pointer to the other object RRS feed

  • Question

  • Ok so I want to make a class that will move an object from one position to another like soo.

    class Mover
       Mover(Vector2 *StartingPos, Vector2 &EndingPos, float time)
       this->StartingPos = StartingPos;
       Vector2 *StartingPos;
       Vector2 EndingPos;
       Vector2 Vel;

    Of course i didnt finish this but you do get my point right? I want a class that will move an objects position. I do know that xna has a ref keyword so will this work?

    public class Mover
        Vector2 StartintPos;
        Mover(ref Vector2 StartPos, Vector2 EndPos, float time)
          StartingPos = StartPos;

    Wednesday, August 8, 2012 7:27 PM

All replies

  • ref when used with a struct type such as Vector2 is essentially passing the pointer to the structure.  The way you are using it in your example is just a slightly more efficient way of passing a vector to the method (passing by ref instead of by value), then you are copying the value of the vector into the member StartingPos.  If you were to modify StartPos in the method, these changes would be seen in the variable passed to the method.  There are limits to using the ref keyword though.  You cannot pass a property to the method for that parameter, nor can you pass a member of a List<Vector2> or similar collection.
    Wednesday, August 8, 2012 7:37 PM
  • ok now how do i return a referense?

    I have tried

    public ref Vector2 GetRefPosition()


         return pos;


    this fails....

    Wednesday, August 8, 2012 8:23 PM
  • You can't return a reference to a value type in C# or any CLR language. See this post:

    I am not sure what you are trying to accomplish overall, but it seems light a simpler design would be to have a Move() method of the objects you are trying to move that does what the Mover does.

    Friday, August 10, 2012 7:33 PM