Is it possible to create a dictionary that holds different classes?

Say you have the classes : Block, Lever and Enemy.

Is there a way to hold all 3 in the same dictionary. I’d like to create a dictionary that is able to return whichever is occupying a given position. There is more than 3 classes really, I’d like something more practical than holding the gameobject as a value and then analyzing what it is.

Make them derive from the same base class, then you can just define your dictionary as following:

Dictionary<int, SharedBaseClass> storage;

You could store booleans in such base class to know the type of object you’re dealing with:

SharedBaseClass entity = storage[index];

if(entity.isEnemy) 
{
    Enemy enemy = (Enemy)entity;
}
1 Like

Awesome, thank you sir

You don’t need the booleans. You can simply use the is keyword as shown below. The output of the following code reported that the first entry is a Vehicle and a Car while the second entry is a Vehicle and a Truck.

Dictionary<int, Vehicle> vehicles;

// Use this for initialization
void Start () {
    vehicles = new Dictionary<int, Vehicle>();

    Car sedan = new Car();
    vehicles[0] = (Vehicle)sedan;

    Truck semiTrailer = new Truck();
    vehicles[1] = (Vehicle)semiTrailer;

    if (vehicles[0] is Vehicle)
    {
        Debug.Log("Entry 0 is a Vehicle!");
    }

    if (vehicles[0] is Car)
    {
        Debug.Log("Entry 0 is a Car!");
    }

    if (vehicles[0] is Truck)
    {
        Debug.Log("Entry 0 is a Truck!");
    }
 
    if (vehicles[1] is Vehicle)
    {
        Debug.Log("Entry 0 is a Vehicle!");
    }

    if (vehicles[1] is Car)
    {
        Debug.Log("Entry 0 is a Car!");
    }

    if (vehicles[1] is Truck)
    {
        Debug.Log("Entry 0 is a Truck!");
    }
}
2 Likes

Yeah, but keep in mind that you can’t use this for inherited objects in this way:

{
    public class Vehicle { }
    public class Car : Vehicle { }

    public class Program
    {
        public static void Main(string[] args)
        {
            var obj = new Car();
            Console.WriteLine("Is car a vehicle? " + obj is Vehicle);
        }
    }
}

Outputs: Is car a vehicle? False

No… the ‘is’ operator will test anywhere in the inheritance/implementation chain.

Though I could see a big problem with your existing code. Without parens around the ‘obj is Vehicle’, what you’re really saying is:

("Is car vehicle? " + obj) is Vehicle

Which is asking if a string is a Vehicle. It just performs the operations from left to right. So string + obj = string, string is Vehicle = false.

You’re probably getting printed out just:

False

Corrected to:

Console.WriteLine("Is car a vehicle? "+ (obj is Vehicle));

I get:

Is car a vehicle? True

2 Likes

Oh, you’re right the brackets are needed. Sorry. :stuck_out_tongue: