Cxyda
Cxyda

Reputation: 87

C# Store Class Type in a Dictionary/List

Is there a way to store the class type and not an instance of a class in my dictionary/list?

I want to do something like this:

public class FoodNeed : BaseNeeds
{
    public Dictionary<Type, float> consumptionlist = new Dictionary<Type, float>();

    public FoodNeed()
    {
        consumptionlist.Add (Meat, 0.3f);
    }
}

Meat is is class and instead of adding a "new Meat()" to the dictionaray i just want to store the type (beacause i think it's not necessary to create the complete instace just for the type), is that possible? Or do i have to store for example "Meat" as string and parse this later on. Or is something like this a big no-no and this has to be done differently.

Thank you for your help

Upvotes: 2

Views: 2105

Answers (2)

madoxdev
madoxdev

Reputation: 3880

Please use typeof,

public class FoodNeed : BaseNeeds
{
    public Dictionary<Type, float> consumptionlist = new Dictionary<Type, float>();

    public FoodNeed()
    {
        consumptionlist.Add (typeof(Meat), 0.3f);
    }
}

Upvotes: 1

Peter Rasmussen
Peter Rasmussen

Reputation: 16922

I believe you are looking for typeof to get the type of meat:

public class FoodNeed : BaseNeeds
{
    public Dictionary<Type, float> consumptionlist = new Dictionary<Type, float>();

    public FoodNeed()
    {
        consumptionlist.Add(typeof(Meat), 0.3f);
    }
}

Upvotes: 6

Related Questions