tags:

views:

729

answers:

3

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

A: 

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);
    }
}
Michael
A: 

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
   }
}
BFree
This should work. Thanks!
RCIX
I think I'll actually derive from GraphicsDevice to offer the extensions i need so my code can use the fancy addons I write but any stuff that uses a regular graphics device will still work. Since this answer inspired that idea however it will still be the accepted answer. Thanks!
RCIX
I wasn't sure if GraphicsDevice was sealed or not (for some reason I assumed it was) which is why I offered a "wrapper" solution instead.
BFree
if you're gonna downvote ppl, post a reason...
BFree
??? I didnt downvote you. i upvoted you! i cant even downvote yet...
RCIX
I wasn't referring to you, but someone did downvote... Meh, whatever...
BFree
Hmm, someone downvoted mine too.
Michael
+2  A: 

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.

Joel Martinez
My main problem with using a new vector is that it is 2 or 3 times longer than just using a variable.
RCIX