Search code examples
c#iosgenericsaot

How can I generate any generic type at runtime on AOT platforms?


I need to generate generic types at runtime on AOT platforms. I know of a "workaround" that hints the compiler to generate a specific generic class by creating a dummy method in the code:

public void DoDummy(){
    var a1 = new MyClass<MyType>();
}

Unfortunately, this specific workaround will not work for me as I have over a few hundred thousand (no exaggeration) possible combinations of types that could be created.

Is there any way to accomplish what I am trying to achieve?


Solution

  • While not a perfect solution, I found that something better than a brute force list of all combinations (the normal workaround) can be achieved with a generic interface and a generic abstract class.

    Create a generic class, such as this:

    public abstract class GenericBase<T>
    {
        public static bool AOTConstruct()
        {
            bool b = (new GV<T>() == null); // Where GV<T> is a Generic Class.
            // Do similar for all Generic Classes that need to be AOT compiled.
            return b;
        }
    }
    

    Then create a generic interface, such as this:

    public interface IGenericValue<T>
    {
        GenericBase<T> ConstructGenericBase();
    }
    

    Now, System Types can be AOT compiled for the Generic classes listed in AOTConstruct by being declared as the type for a class implementing the interface, like so:

    public class SystemTypes : IGenericValue<float> // Implement IGenericValue for other Types.
    {
        GenericBase<float> IGenericValue<float>.ConstructGenericBase()
        {
            throw new NotImplementedException();
        }
    }
    

    The same can be done for any custom class, either in the same class as the System Types, or as part of the custom class' declaration (which I prefer for clarity).

    It is disappointing to have to update the SystemTypes for new System-level Types to support, and to update the AOTConstruct for new Generic Classes that need support, but it works for compiling to iOS and does not require all combinations to be listed.