Reputation: 1531
My primary languages growing up were PHP, Python, etc. In these languages it is very easy to initialize dictionary-style objects (so-called associative arrays in other languages).
I am using C# for a project now and find the method of initializing a large dictionary to be quite cumbersome and figured I may be doing something wrong, or against best practices. For example, here is a dictionary I want to keep some project data in:
//Campaign dictionary
public Dictionary<int, Dictionary<string, Dictionary<object, Dictionary<string, object>>>> campaignData = new Dictionary<int, Dictionary<string, Dictionary<object, Dictionary<string, object>>>>();
It seems like there is a better way to do this. The code is not readable at all and just to initialize a simple 3-4 stage hierarchy is a massive line of code. If you know of a way, please let me know! Thank you
EDIT ** I have drawn out the type of structure I am trying to obtain. Game progress data that can be bundled and written to a save file:
Upvotes: 0
Views: 52
Reputation: 219077
Don't use dictionaries for everything. A dictionary is essentially a collection of values or objects identified by unique keys. Unless that's specifically what you're using, a dictionary is the wrong tool.
Instead, consider the semantics of the structure you want and build that structure. For example, in the image in the question you have:
So something like this:
public class Objective
{
public Vector3 Position { get; set; }
public bool IsCompleted { get; set; }
}
public class Level
{
public IEnumerable<Objective> Objectives { get; set; }
public bool LevelIsComplete { get; set; }
}
Maybe you further have a list of levels, contained perhaps within a "game" or something of that nature. Etc.
The point is that C# embraces static typing in classes, where you're trying to use very loose typing in associative arrays. Build the structures you want into classes, include the necessary logic within those classes where that logic semantically belongs, and the code will read a lot better.
Upvotes: 2
Reputation: 3149
I never encountered such a multi-level map structure but if you want to do it cleaner, you need to define those map structures as types. This makes the code both readable (in terms of declaration length) and understandable.
Of course you would use sensible names for the types and not TypeOutermost
.
internal class Program
{
public static void Main(string[] args)
{
var campaignData = new Dictionary<int, TypeOutermost>();
}
public class TypeOutermost : Dictionary<string, TypeMid>
{
}
public class TypeMid : Dictionary<object, TypeInnermost>
{
}
public class TypeInnermost : Dictionary<string, object>
{
}
}
Upvotes: 0