Friday, April 16, 2010

C#: Collection Initializers


Developing games requires countless amounts of properties and settings that often straddle the line between 'code' and 'data' quite akwardly. C# Collection Initializers allow very nice inline placement of these sorts of values.

Here is a snippet of some weapon data for a 2D top-down shooter:



new List() {
    new SWeaponData() {
        ReloadTime = 0.15f,
        Speed = 15.0f,
        Damage = 0.3f,
        Offset = new Vector2(0.0f, -10.0f),
    },
    new SWeaponData() {
        ReloadTime = 0.15f,
        Speed = 15.0f,
        Damage = 0.3f,
        Offset = new Vector2(0.0f, 10.0f),
    },
},


This sort of code/data is easy to modify and understand, and really just is an excellent fundamental language feature that you will miss using C++.

Keep in mind that this code runs -after- the constructors, so you can have default values in your constructor, and then on a per-instance basis override any of the values. Very useful!


// Instant variation!
Turret t = new Turret() { Texture = "MagicTurret", SE = "MagicShoot", Health = 20 };


Sensible defaults with the occasional case-specific override gives your code an enormous amount of flexibility.

No comments:

Post a Comment