I am working on a pathfinding program / algorithm, and I have the following class:
[System.Serializable]
public class UnitTileCosts
{
int[] tileCosts;
public UnitTileCosts()
{
//empty constructor uses default value of 1 for all fields
GenerateDefaults();
}
public UnitTileCosts(Dictionary<TileType,int> costs)
{
GenerateDefaults();
foreach(var pair in costs)
{
tileCosts[(int) pair.Key] = pair.Value;
}
}
void GenerateDefaults()
{
tileCosts = new int[System.Enum.GetNames(typeof(TileType)).Length];
for(int i = 0; i < tileCosts.Length; i++)
{
tileCosts[i] = 1;
}
}
public int GetTileCost(TileType tile)
{
return tileCosts[(int) tile];
}
}
Is this better or worse than simply using a Dictionary<TileType, int>
in the first place?
Using the Dictionary
(that is passed in to the constructor), I would need to check if the key exists because I only care about those values that differ from the result. (Which, admittedly, is easily doable with TryGetValue
and an OUT parameter)
I would think that an array of ints would serialize better than a dictionary, to boot.
Is casting from the enum to the int
acceptable in this instance? I understand that enums are designed to avoid magic numbers, but in this case I only care about the numbers (and not the magic), so I think it might be reasonable.