Home > front end >  How to assign class type to generic Type <T>?
How to assign class type to generic Type <T>?

Time:11-14

I have a class to execute particular logic as below:

public abstract class BaseSchema<T> : iMyInterface
    {
        public List<T> GetSchemaObjects<T>(string csvData) where T : iMyInterface
        {
            var records = new List<T>();
            using (var streamReader = new StreamReader(csvData))
            {
                using (var csvReader = new CsvReader(streamReader, CultureInfo.InvariantCulture))
                {
                    records = csvReader.GetRecords<T>().ToList();
                }
            }
            return records;
        }
    }

Now I want to call this method with a Class as parameter. I have Type object for the class. How do I assign while calling?

public List<T> GetTestSchema<T>(string versionNumber, string schemaName) where T : iMyInterface
        {
Type[] allSchemaTypes = Assembly.GetExecutingAssembly().GetTypes()
                                .Where(t => t.IsClass && t.Namespace.StartsWith($"{schemaNamespace}") 
                                        && !t.GetCustomAttributes(typeof(ObsoleteAttribute), true).Any())
                                .ToArray();            
int indexNumber = GetIndexNumberOfRequiredVersion(versionNumber);
            Type schemaType = allSchemaTypes
                                .Skip(indexNumber)
                                .Where(x => x.Name.Equals(schemaName) && interfaceType.IsAssignableFrom(x))
                                .FirstOrDefault();
            var objj = (iMyInterface)schemaType.Assembly.CreateInstance(schemaType.ToString());
            //Type objjType = Type.GetType(objj);
            return objj.GetSchemaObjects<schemaType>(@"CSV Path"); // This line gives an error as Cannot implicitly convert type List<schemaType> to List<T> but generic should accept it. Isn't it?
        }

CodePudding user response:

You can use MakeGenericMethod something like:

MethodInfo getSchemaObjectsMethod = typeof(iMyInterface).GetMethod("GetSchemaObjects");
MethodInfo getSchemaObjectsGeneric = getSchemaObjectsMethod.MakeGenericMethod(schemaType);
return getSchemaObjectsGeneric.Invoke(null, new object[] { "CSV Path" });

See: How do I use reflection to call a generic method?

  • Related