I have the following scenario:
I have three classes, let's call them A
, B
and C
. All they have in common is that they inherit from the same interface, ISomeInterface
and that they are classes that are mapped to entities using Entity Framework.
I have a method that received a List of objects that implements this interface, but the objects themselves will be instances of A
, B
or C
.
The method shell looks like this
public void MyMethod(List<ISomeInterface> entityList)
{
foreach(var entity in entityList)
{
ProcessEntity(entity);
}
}
Now, the problem is with the ProcessEntity
method. This is a generic method, that needs to retrieve the table of matching elements from the database according to the type or entity, so it looks like this:
public void ProcessEntity<T>(T entity)
{
using( var repository = new DbRepository())
{
var set = repository.Set<T>();
...
}
}
The problem is that the line var set = repository.Set<T>();
fails because T
is ISomeInterface
in this case, and not the actual type( A
, B
or C
), so it gives an exception that is can't relate to the type given, which is understandable.
So my question is: How can i call ProcessEntity with the actual type of the object inside the list, and not the interfacetype that they implements.
In the same way, you can derive a generic class from another generic class that derived from a generic interface. You may be tempted to derive just any type of class from it. One of the features of generics is that you can create a class that must implement the functionality of a certain abstract class of your choice.
From the point of view of reflection, the difference between a generic type and an ordinary type is that a generic type has associated with it a set of type parameters (if it is a generic type definition) or type arguments (if it is a constructed type). A generic method differs from an ordinary method in the same way.
You can apply dynamic
keyword when passing entity to ProcessEntity. In this case actual type of entity will be determined at runtime.
public void MyMethod(List<ISomeInterface> entityList)
{
foreach(var entity in entityList)
{
dynamic obj = entity;
ProcessEntity(obj);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With