Dobi
Dobi

Reputation: 125

C# mimic associative array of unknown key-number (like in PHP)

Is there a possibility to create sth. like an associative array like in PHP? I don't plan to create a game with some player-data, but I could easily explain this way what I want:

player["Name"] = "PName";
player["Custom"]["Gender"] = "Female";
player["Custom"]["Style"] = "S1";
player["Custom"]["Face"]["Main"] = "FM1";
player["Custom"]["Face"]["Eyes"] = "FE1";
player["Custom"]["Height"] = "180";

Also the length has to be dynamic, I don't how many keys there will be:

player["key1"]["key2"]=value
player["key1"]["key2"]["key3"]["key4"]...=value

What I need is sth. I could address like:

string name = player["Name"];
string gender = player["Custom"]["Gender"];
string style = player["Custom"]["Style"];
string faceMain = player["Custom"]["Face"]["Main"];
string faceEyes = player["Custom"]["Face"]["Eyes"];
string height = player["Custom"]["Height"];

Or in some way similar to this.

What I tried till now:

Dictionary<string, Hashtable> player = new Dictionary<string, Hashtable>();
player["custom"] = new Hashtable();
player["custom"]["Gender"] = "Female";
player["custom"]["Style"] = "S1";

But the problem starts here (only works with 2 keys):

player["custom"]["Face"] = new Hashtable();
player["Custom"]["Face"]["Main"] = "FM1";

Upvotes: 0

Views: 118

Answers (1)

PlageMan
PlageMan

Reputation: 792

C# is strongly typed so it seems not easy to replicate this exact behavior.

A "possibility" :

public class UglyThing<K,E>
{
    private Dictionary<K, UglyThing<K, E>> dicdic = new Dictionary<K, UglyThing<K, E>>();

    public UglyThing<K, E> this[K key] 
    { 
        get 
        {
            if (!this.dicdic.ContainsKey(key)) { this.dicdic[key] = new UglyThing<K, E>(); }
            return this.dicdic[key];
        } 
        set
        {
            this.dicdic[key] = value;
        } 
    }

    public E Value { get; set; }
}

Usage :

        var x = new UglyThing<string, int>();

        x["a"].Value = 1;
        x["b"].Value = 11;
        x["a"]["b"].Value = 2;
        x["a"]["b"]["c1"].Value = 3;
        x["a"]["b"]["c2"].Value = 4;

        System.Diagnostics.Debug.WriteLine(x["a"].Value);            // 1
        System.Diagnostics.Debug.WriteLine(x["b"].Value);            // 11
        System.Diagnostics.Debug.WriteLine(x["a"]["b"].Value);       // 2
        System.Diagnostics.Debug.WriteLine(x["a"]["b"]["c1"].Value); // 3
        System.Diagnostics.Debug.WriteLine(x["a"]["b"]["c2"].Value); // 4

Upvotes: 1

Related Questions