I use XNA, and one of the things i do a lot is pass around data as Vector2s. Now, a lot of the objects in XNA (such as a graphics device and such), inste3ad of containing a Vector2 that tells you the size of the viewport, they offer separate Width and Height methods. Is there some way to add a Vector2 property to them so i can get that data without manually building a new vector2 everytime i need it? i guess what i want is something like "extension properties"...
Extension properties aren't supported, but you can still code an extension method:
class ExtensionMethods
{
public static Vector2 GetViewSize(this GraphicsDevice device)
{
return new Vector2(device.Viewport.Width, device.Viewport.Height);
}
}
You can use Michael's approach, but that does in fact build a new Vector2 every time. If you really only want the Vector2 to be created once, you can wrap the class you want, and provide your own Vector2 property:
public class GraphicsDeviceWrapper
{
private Vector2 vector;
public GraphicsDeviceWrapper(GraphicsDevice device)
{
this.vector = new Vector2(device.Viewport.Width, device.Viewport.Height);
this.Device = device;
}
public Vector2 Vector
{
get{return this.vector;}
}
public GraphicsDevice Device
{
get; private set
}
}
Vector2 is a value type ... honestly, you don't really have to worry too much about creating new instances because they're created on the stack. Every time you can the .Vector property it's going to make a new instance anyways.
you don't have to worry about it though because value types do not invoke the garbage collector. Thus, the biggest reason to try to instantiate once is nullified (ie. the GC).
that being said, for larger structs such as a Matrix, you may want to consider passing them byref to avoid new allocations on the stack.