Search code examples
c#genericsdynamicgeneric-type-argument

Call method on object on which generic type is not known except at runtime? Should I just use a dynamic?


say I have a class

public abstract class A<T>
{
     public T GetT{get;}

     public ISomeInterface AMethod{get;}
}

Then I have some other method in another class where I take an object and I want to check it is of type A<> then if it is get the type of T and call the method AMethod. So I'm doing this:

if (theObject.GetType().GetGenericTypeDefinition() == typeof (A<>))
{
    Type TType = theObject.GetType().GetGenericArguments()[0];            
    dynamic dynamicObject= theObject;
    ISomeInterface filter = dynamicObject.AMethod;
    //...some other stuff using TType
} 

Is there a way to do this without using the dynamic object, since I can't declare the type of the variable using the TType or using the generic type defintion A<> at runtime...


Solution

  • If you're able to, put all the non-generic stuff in an abstract non-generic base class:

    public abstract class A
    {
         public ISomeInterface AMethod{get;}
    }
    
    public abstract class A<T> : A
    {
         public T GetT{get;}
    }
    

    Then you can just use:

    A foo = theObject as A;
    if (foo != null)
    {
        ISomeInterface filter = foo.AMethod;
    }