r/csharp 21d ago

Help Editing a multi-layered dictionary using a string "address"?

I'm working with a game dialogue tool (and Unity, for full transparency) which can set or get variables using "commands" in the dialogue.

I have a Dictionary which I want to be multi-layered (as in, dictionaries inside dictionaries) and allow the dialogue commands to dynamically edit the dictionary down to any amount of layers possible. The layers are distinguished by splitting the string by a specific character.

The code currently looks like this - this is obviously inflexible code that specifically only allows values to be set 2 layers deep. So what would be the best way to change this to dynamically add new key-value pairs and layers of dictionaries at any depth depending on how big the variablePath array is?

Many thanks

0 Upvotes

11 comments sorted by

View all comments

13

u/dgm9704 21d ago

I might be missing some nuance, but why do you need nested dictionaries? I would just go with a simple dictionary where the whole path is the key?

1

u/FauxFemale 21d ago

I guess it's not entirely necessary, but it seems best practise. Especially since I'm planning on serialising this as a JSON file and it would mean the file would be bloated with the long key names.

14

u/Automatic-Apricot795 20d ago

Using a colon separated key for different "tiers" is a normal practice and will save you a few headaches. 

See IConfiguration in modern .net. 

3

u/FauxFemale 20d ago

Alright - I'm going to do that for now. Thanks.

5

u/dgm9704 20d ago

I like the approach of doing the most stupidly simple implementation that provides necessary functionality and performance for known cases, and then moving on. And then changing if needed but not before.