Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a generic method with the correct derived type

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.

like image 480
Øyvind Bråthen Avatar asked May 31 '12 09:05

Øyvind Bråthen


People also ask

Can a generic class be derived from another generic class?

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.

How does a generic method differ from a generic type?

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.


1 Answers

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);
  }
}
like image 131
Sergey Berezovskiy Avatar answered Oct 20 '22 15:10

Sergey Berezovskiy