Search code examples
c#generic-programminggenerics

C# generic How to define that T is Base<Tp> : where Tp : Base<Tp> and Call Base<Tp> method


I have confusing situation.

Base Generic Type and successor

public abstract class BaseType<TEntity> : where TEntity : BaseType<TEntity>
public class AnyType : BaseType<AnyType>

It looks like a generic loop)))

I need Method like

public void Method<T>(T data)
{
if(typeof(T).IsSubclassOf(BaseType<????>))
 convert data to BaseType<???> and exec BaseType<>'s method
else
//Do that
}

In generic Method i need to defines that T is BaseType and exec method on it. How can I do that????


Solution

  • You can use reflection and work your way up the hierarchy using Type.BaseType. Note that depending on the exact concrete class, the base type could still be an open generic type, e.g.

    class Foo<T> : BaseType<T>
    

    You can use Type.IsGenericTypeDefinition and Type.GetGenericTypeDefinition to try to work your way to BaseType<>. Basically you want to find out whether any class in the inheritance hierarchy has a generic type definition which is typeof(BaseType<>). Just be glad you're not dealing with interfaces, which make the whole thing even harder :)