Bluperman949
Bluperman949

Reputation: 1

C# - Dictionary that whose value is a List of multiple Types

I'm trying to make a "Block" class for a side-scrolling cave game in Unity 2D. I'm looking to have a HashMap/Dictionary whose key is and int (the block's ID) and the value is a List of multiple types, say, the block's texture (Tile), display name (string), hardness (int), or relationship with gravity (bool).

I'd like it to work like this, but I know this isn't how C# works.

Dictionary<int, List<Tile, int, string, bool>> blockProperties;

Upvotes: 0

Views: 488

Answers (1)

Chris Hutchinson
Chris Hutchinson

Reputation: 9212

Create a data structure to contain the types:

class BlockDescriptor 
{
    public Tile Tile { get; }
    public int Hardness { get;}
    public string DisplayName { get; }
    public bool HasGravity { get; }

    public BlockDescriptor(Tile tile, int hardness, string name, bool gravity)
    {
        Tile = tile;
        Hardness = hardness;
        DisplayName = name;
        HasGravity = gravity;
    }
}

Then you can store them in a dictionary:

Dictionary<int, BlockDescriptor> blockProperties = new Dictionary<int, BlockDescriptor>();
blockProperties.Add(0, new BlockDescriptor(/* Tile */, 1, "Block A", false);
blockProperties.Add(1, new BlockDescriptor(/* Tile */, 2, "Block B", true); 

Alternatively you could use a tuple:

var blockProperties = new Dictionary<int, (Tile, int, string, bool)>();
blockProperties.Add(0, (/* Tile */, 0, "Block A", false));
blockProperties.Add(1, (/* Tile */, 1, "Block B", true));

I recommend choosing a data structure, because you can implement various interfaces such as IEquatable, IEqualityComparer, to affect the behavior within LINQ queries, containers, etc. Additionally, it provides potential for various introspection properties (e.g. IsUnbreakable, HasTileWithTransparency), or methods (e.g. CalculateHardness)

Upvotes: 4

Related Questions