Search code examples
filehelpers

Create FileHelperEngine from Type variable


I am attempting to create an instance of FileHelperEngine<> using a generic type. For example this works for List

    public static IList CreateList(Type type)
    {
        var genericListType = typeof(List<>).MakeGenericType(type);
        return (IList)Activator.CreateInstance(genericListType);
    }

Is it possible to do something similar for FileHelperEngine<>?

I tried

    public static FileHelperEngine CreateFileHelperEngine(Type type)
    {
        var genericFileHelperEngineType = typeof (FileHelperEngine<>).MakeGenericType(type);
        return (FileHelperEngine)Activator.CreateInstance(genericFileHelperEngineType);
    }

And get this error

Unable to cast object of type 'FileHelpers.FileHelperEngine`1[NachaParser.Model.EntryDetail.PpdEntryModel]' to type 'FileHelpers.FileHelperEngine'.


Solution

  • This would not work because you are attempting to go from the generic engine to the standard engine. The generic engine does not inherit from the standard engine so you can't directly cast.

    The following code should work for you:

        public static FileHelperEngine<T> CreateFileHelperEngine<T>() where T : class
        {
            var genericFileHelperEngineType = typeof(FileHelperEngine<>).MakeGenericType(typeof(T));
            return (FileHelperEngine<T>)Activator.CreateInstance(genericFileHelperEngineType);
        }
    

    The problem is that you need to have the type of T not as a Type variable but as as a passed generic argument. Unfortunately, the generic engine is based of EngineBase<T> with IFileHelperEngine<T> as an interface it implements so you can never get a FileHelperEngine<T> to a FileHelperEngine.

    Your only other option is to use:

        public static FileHelperEngine CreateFileHelperEngine(Type type)
        {
            if (!type.IsClass)
                throw new InvalidCastException("Cannot use '" + type.FullName + "' as it is not a class");
    
            return new FileHelperEngine(type);
        }