Passing Type variable to generic type: Variable not found.

I’m just trying to pass a type to a generic method, but it’s giving me a syntax error; Error 1 The type or namespace name ‘type’ could not be found (are you missing a using directive or an assembly reference?)

for (int i = 0; i < Loadout.Count; i++)
        {
            for (int n = 0; n < Loadout.ElementAt(i).Value.Count(); i++)
            {
                Type type = Loadout.ElementAt(i).Key;
                Game.Manager.SpawnItem(Detach<type>(i, gameObject), transform.position);
            }
        }

It’s referring to my Type variable (type) in the Detach generic method. It can’t find type even though it’s declared and initialized right above it.

And the dictionary DOES use Type for it’s key:

public Dictionary<Type, Item[]> Loadout = new Dictionary<Type, Item[]>();

You cannot pass a variable of Type “System.Type” as a generic parameter to a generic function directly.

The reason is: Generic parameter are replaced when the code is compiled. Variables store values when the code executes.

One solution is to replace the generic function with a non-generic that accepts the type as a normal parameter

void Detach(Type t, int i, GameObject go) {
    ...
}

This works, if you only use the generic parameter in a “typeof(T)” - statment, but if you use the generic parameter in another generic way (e.g. Dictionary) then you would have to replace that call again (e.g. with “Hashtable”)…

If you are not afraid of C# internas and dynamic type generation and if you are not deploying on iOS (because that does not support dynamic code generation at all), then you can compile the correct call to Detach at runtime. Remember that this is significant slower than any “non-generic code with lots of casts”.

MethodInfo genericFunction = GetType().GetMethod("Detach");
MethodInfo realFunction = genericFunction.MakeGenericMethod(Loadout.ElementAt(i).Key);
var ret = (GameObject)realFunction.Invoke(this, new object[]{ i, gameObject });
Game.Manager.SpawnItem(ret, transform.position);

This code assumes that “Detach” is public and declared in the same class as the code above is. And the parameter of Detach are exactly “int” and “GameObject” and the return type is “GameObject”.