Search code examples
c#unity-game-enginehashtable

Hastable of hastables, .Add access problem


I'm trying to re-create an old script that I already have working in Ruby, and I'm doing it with C# because I'm migrating a project of mine to Unity. This Script searches for files inside folders inside 3 different levels. This is what I mean, is a filepath, Folder1/Folder2/Folder3/files_are_here.

Explanation: My working script (on Ruby) performs that by searching every "Folder1", and assigning the name of each one as a Key to a Hashtable. (So now I have a Hashtable in which every key is the name of a Folder that will represent the "Folder1" part of the filepath that I mentioned above). I've also defined as a Value for each of this keys, a new Hashtable.

Thereafter, for each "Folder1" in my Hashtable, it performs a second search for every "Folder2" that is inside each "Folder1", and here I add each Folder name of each "Folder2", as a Key for the Hashtable of the "Folder1" that contains that "Folder2".

For each "Folder2" for each "Folder1", I search each "Folder3" inside that "Folder2" that is inside that "Folder1", etc.

I'm having a problem. I have my main Hashtable with every key representing a "Folder1", and I can perform the search for every "Folder2" inside every "Folder1".

My problem is when I try to do:

main_hash[first_folder.Key].Add(folder_2_name, new Hashtable())

It says that ('object' does not contain a definition for 'Add'), but if I:

Debug.Log(main_hash[first_folder.Key])

It prints System.Collections.Hashtable, so it is a Hashtable, and it should have to have an .Add() Method.

What is going on? Anyone knows?. (Even if you tell me to do it other ways so I can improve it, I would love to know why I'm having that error).


Solution

  • It is in fact a HashTable, but main_hash, which contains it is an object collection. If you're certain that you will always find a hash table in this collection, you can force it to resolve as a hash table with a cast:

    ((HashTable)main_hash[first_folder.Key]).Add(...)
    

    otherwise you can take a typed reference and test it:

    var table = main_hash[first_folder.Key] as HashTable;
    if(table != null)
    {
        table.Add(...);
    }