Search code examples
c#genericstypesgeneric-type-argument

How to get all generic parameters of class?


I have an abstract class with a few or many (from 1 all the way up to 16) generic parameters like so:

public abstract class ComponentSystem<F1> : ComponentSystemBase
    where F1 : IComponent
{ }

public abstract class ComponentSystem<F1, F2> : ComponentSystemBase
    where F1 : IComponent
    where F2 : IComponent
{ }

public abstract class ComponentSystem<F1, F2, F3> : ComponentSystemBase
    where F1 : IComponent
    where F2 : IComponent
    where F3 : IComponent
{ }

public abstract class ComponentSystem<F1, F2, F3, F4> : ComponentSystemBase
    where F1 : IComponent
    where F2 : IComponent
    where F3 : IComponent
    where F4 : IComponent
{ }

Now I have a base class that contains a list of types like so:

public abstract class ComponentSystemBase
{
    public List<Type> Filters { get; private set; }
    public abstract void Init();
    public abstract void Update();
    protected internal void PopulateFilterList(Type[] filters)
    {
        // oneliner?
        foreach (Type filter in filters)
        {
            Filters.Add(filter);
        }
    }
}

Now my question is, how do I get all the generic parameters in a type array so I can pass it to my function who adds it to the list?

Is there a function to get all the generic parameters, do I have to do it manually for each class?

If something is unclear let me know so i can clarify!


Solution

  • Reflection to the rescue!

    Type[] types = GetType().GetGenericArguments();