Hey All Im Trying to build a way to serialize KeyValuePair(mostly to learn) and have a Q.

Okay so I have a class that represents my own key value pair system (I know you’ll probably LoL at it but…)
what I’m trying to do now is make it so you can access values using key references like you would with a Dictionary.

<I Am Calling This Collection A “Table”>

Example: Debug.Log(myTableVar [Key]);

Here Is The Class:

	[System.Serializable]
		public class TableItem <TKey, TValue>{
			public TKey Key;
			public TValue Value;
			public TableItem(TKey Key, TValue Value){
				this.Key = Key;
				this.Value = Value;
			}
		}
		[System.Serializable]
		public class Table <TKey, TValue> {
			static System.Type keyType = typeof(TKey);
			static System.Type valueType = typeof(TValue);
			static List <TKey> keys = new List<TKey> ();
			static List <TValue> values = new List<TValue> ();
			public IEnumerator GetEnumerator(){
				for (int i =0; i < keys.Count; i++) {
					yield return new TableItem<TKey,TValue> (keys[i],values[i]);
				}
			}
			public void Add (TKey Key, TValue Value){
				if (Key.GetType () == keyType && Value.GetType () == valueType) {
					if(!keys.Contains (Key)){
						keys.Add (Key);
						values.Add (Value);
					}
				}
				else {
					Debug.LogError ("Cannot Convert: <"+Key.ToString ()+", "+Value.ToString ()+"> To: <" + keyType.ToString ()+", "+ valueType.ToString()+">.");
				}
			}

And here is the script that is running it:

	table.Add (0, "String");//<-----This Works
		TableItem <int,string> i = new TableItem<int, string> (10, "DDD");//<-----This Works
		table.Add (i.Key, i.Value); //<-----This Works
		foreach(TableItem<int,string> kvp in table){//<-----This Works
			Debug.Log (kvp.Key + " : " + kvp.Value);
		}
		Debug.Log (table [0]);//<-----This Does Not Work (How Do I Make It Work???)***

Thanks In Advance!

I believe you’re asking how to overload the [ ] operator in C#.

1 Like

Thanks A lot, JoeStrout!!! That works great I had to make a few changes to adhere to my needs but with this code it does the trick:

    public TValue this[TKey key]{
                get{
                    for(int i = 0; i < keys.Count; i++){
                        if(keys[i].Equals (key)){
                            return values[i];
                        }
                    }
                    return default (TValue);
                }
                set{
                    for(int i = 0; i < keys.Count; i++){
                        if(keys[i].Equals (key)){
                            values[i] = value;
                            break
                        }
                    }
                }
            }

Your use of statics is probably going to bite you.

1 Like

Yea I changed them to private because of that IDK what I was thinking…