I'm working on a project that imports Data from csv/xml files and stores the chosen data in a SQL-database. I encountered a problem where I had to call certain generic methods with type parameters which are dependent and I don't want to code each possible case.
Is there a way to pass type parameter in a variable fashion?
I already solved the problem in a hacky way. I'm just curious if there is a recommended way since this is common scenario.
EDIT: My approach looks something like this:
I have generated a Func<dynamic>
that returns a new instance of a certain entity and stored them all in Dictionary along with the name of the entity.
Every generic method that I want to call in the mentioned way, got a parameter of the generic type. This way the compiler can figure out the type without the need of writing it explicitly. The only drawback is that I have to pass a dummy each time.
public abstract class Entity
{
private static readonly Dictionary<string, Func<dynamic>> instantiateNewTypedEntityDelegatesDict;
static Entity()
{
Assembly assembly = Assembly.GetExecutingAssembly();
instantiateNewTypedEntityDelegatesDict = new Dictionary<string, Func<dynamic>>();
foreach (var entityType in assembly.GetTypes().Where(x => x.IsSubclassOf(typeof(Entity))))
{
CreateInstantiateNewTypedEntityDelegate(entityType);
}
}
private static void CreateInstantiateNewTypedEntityDelegate(Type entityType)
{
NewExpression newExpr = Expression.New(entityType.GetConstructor(new Type[0]) ?? throw new InvalidOperationException());
instantiateNewTypedEntityDelegatesDict.Add(entityType.Name, Expression.Lambda<Func<dynamic>>(newExpr).Compile());
}
public static dynamic CreateNewTypedEntity(string entityName)
{
return instantiateNewTypedEntityDelegatesDict[entityName]();
}
}
And a sample prototype of a method I want to call:
public TEntity GenericMethodIWantToCall<TEntity>(TEntity dummyEntity /*other paramters do not matter*/)