Oyyou Oyyou - 14 days ago 5
C# Question

Calling a method when initializing object

I'm looking at a way of cleaning up some code. I have the below

var sprite1 = new Sprite(_content.Load<Texture2D>("Content/Block.png"));
sprite1.Position = new Vector2f(100, 100);
sprite1.SetInput(Key.A, Key.D, Key.W, Key.S);

var sprite2 = new Sprite(_content.Load<Texture2D>("Content/Block.png"));
sprite2.Position = new Vector2f(200, 100);
sprite2.SetInput(Key.Left, Key.Right, Key.Up, Key.Down);

_sprites = new List<Sprite>()
{
sprite1,
sprite2,
};


I'd like to initialize the "Sprite" when adding it to the list. But the problem I'm having is the "SetInput" method. That method is optional.

I know this isn't syntactically correct, but below is the sort of thing I'm talking about

_sprites = new List<Sprite>()
{
new Sprite(_content.Load<Texture2D>("Content/Block.png")) { Position = new Vector2f(100, 100), SetInput(Key.A, Key.D, Key.W, Key.S) },
};


As you can see I'm attempting to call a method in a similar to way you can set properties.

Here are the ways I'm thinking of getting around it


  1. Optional parameters constructor for the keys

    public Sprite(Texture2D texture, Key? left, Key? right, Key? up, Key? down)

  2. A second constructor with the keys

    public Sprite(Texture2D texture, Key left, Key right, Key up Key down)

  3. Creating a delegate in the "Sprite" class that is assigned when initialized, and then loop around all the _sprites, calling the method



The code I've put at the start is fine, I'm just wondering if there is a 'better' way?

Thanks.

Answer

What about creating Input class to cleanup it?

internal class Sprite
{
    public Input Input { get; set; }
    ... 
}

internal class Input
{
    public Key Left { get; private set; }
    public Key Right { get; private set; }
    public Key Up { get; private set; }
    public Key Down { get; private set; }

    public Input(Key left, Key right, Key up, Key down)
    {
        Left = left;
        Right = right;
        Up = up;
        Down = down;
    }
}

then you'll get exactly what you want

_sprites = new List<Sprite>()
{
    new Sprite(_content.Load<Texture2D>("Content/Block.png")) 
    { 
         Position = new Vector2f(100, 100), 
         Input = new Input(Key.A, Key.D, Key.W, Key.S),
    },
 };
Comments