0

I'm creating an application that displays "old school" sprites. The location of each sprite is held in a PointF variable.

I would like to update each sprite's position based on a supplied angle and speed.

I have created an extension method over to the PointF class so that this logic is self contained and accessible throughout the application.

The extension method looks like this:

public static class MyExtensions
{
    public static PointF Translate(this PointF point, double angle, double speed)
    {
        point.X += (float)(Math.Sin(angle / 57.2958) * speed);
        point.Y += (float)(Math.Cos(angle / 57.2958) * speed);
        return point;
    }
} 

Currently, the client code that consumes the extended PointF class looks like this:

position = position.Translate(angle, speed);

This works just fine, but I would like to go one step further and completely encapsulate the position update within the extension method. In that case, the client code should work like this:

position.Translate(angle, speed);

To do this, it feels as though I should be passing the existing position value by ref into the method call, but I can't figure out the syntax to do this.

Is this even possible? If so, I would appreciate some guidance...

John Wakefield
  • 477
  • 1
  • 4
  • 15
  • 1
    If `PointF` is a reference type, it will work without `ref`, see [How can I get an extension method to change the original object?](http://stackoverflow.com/q/2326734/33499). If it is a value type (like `struct`), it is not possible, see [Change value inside an (void) extension method](http://stackoverflow.com/q/14333258/33499) – wimh Mar 06 '16 at 21:13
  • Thank you - of course I wasn't seeing the obvious about value types! – John Wakefield Mar 07 '16 at 09:44

0 Answers0