locked
How can I find generic type's type at runtime RRS feed

  • Question

  • Hi,

    This is my generic type  INotification<T,L>

    This is my class  public class OperationWorkingCriteria : DbBaseObject, INotification<WorkOrder, OperationWorkingCriteria>

     INotification<WorkOrder, OperationWorkingCriteria>

    Is it possible to find  at runtime of T as "WorkOrder" and L as "OperationWorkingCriteria"  ?

    Thanks.

    Thursday, December 20, 2012 9:14 PM

Answers

  • I'm not quite sure what you are asking but maybe this is a starting point:

    var criteria = new OperationWorkingCriteria();
    
    foreach (var iface in criteria.GetType().GetInterfaces()) {
         if (iface.GetGenericTypeDefinition() == typeof(INotification<,>)) {
              var args = iface.GetGenericArguments();
              Console.WriteLine(args[0]);
              Console.WriteLine(args[1]);
         }
    }
    

    Basically you search for an interface that matches the generic one and then you extract the generic arguments from it.

    I must say that I find questionable a design that requires such trickery.

    • Marked as answer by Aysegul Kara Thursday, December 20, 2012 9:57 PM
    Thursday, December 20, 2012 9:41 PM

All replies

  • I'm not quite sure what you are asking but maybe this is a starting point:

    var criteria = new OperationWorkingCriteria();
    
    foreach (var iface in criteria.GetType().GetInterfaces()) {
         if (iface.GetGenericTypeDefinition() == typeof(INotification<,>)) {
              var args = iface.GetGenericArguments();
              Console.WriteLine(args[0]);
              Console.WriteLine(args[1]);
         }
    }
    

    Basically you search for an interface that matches the generic one and then you extract the generic arguments from it.

    I must say that I find questionable a design that requires such trickery.

    • Marked as answer by Aysegul Kara Thursday, December 20, 2012 9:57 PM
    Thursday, December 20, 2012 9:41 PM
  • Thank you Mike .

    Thursday, December 20, 2012 9:57 PM