I have a function that takes in a generic type and I want to be able to assign the result of some computation to different lists depending on that type. I'd rather not use reflection because I've learned that it's not exactly best practice.
Here is the gist of what I have so far:
private List<int> List1 = new List<int>();
private List<int> List2 = new List<int>();
private List<int> List3 = new List<int>();
public int SomeFunction<TModel, TEntity>(DbSet<TEntity> context) where TEntity : class where TModel : SuperModel
{
// TEntity could be one of three types: Type1, Type2, or Type3
// If TEntity is of Type1, I want to be able to add something to List1.
// If TEntity is of Type2, I want to be able to add something to List2. And so on.
/* One way to do it */
// ... do some function stuff calculation here...
var result = ...
Type entity_type = typeof(TEntity)
if (entity_type == typeof(Type1))
List1.Add(result);
else if (entity_type == typeof(Type2))
List2.Add(result);
else if (entity_type == typeof(Type3))
List3.Add(result);
}
However, I don't think this is the best way as it relies on reflection for run-time calculation. Is there a way to do it using interfaces or polymorphism?
Another way is to have split this up into three functions, have Type1
, Type2
, Type3
implement three different interfaces and then add a where TEntity : IType1
, where TEntity: IType2
, and where TEntity: IType3
following each of the three function headings.
This doesn't seem to be right either. Any help would be greatly appreciated.