Search code examples
c#crtprecurring

multiple curiously recurring template pattern (CRTP) in c#?


Im trying to implement CRTP interface to my code, but the constraint make me stuck. how to implement the constraints if i have code structure look like this? Is this legal? Thank you.

interface IInterface<T>
    where T: IInterface<T>
{
    //bla bla bla
    T Member { get; set; }
}
interface ITest1<iTest2, iTest1> : IInterface<iTest2>
{
    //bla bla bla
}
interface ITest2<iTest1, iTest3> : IInterface<iTest1>
{
    iTest3 RefMember { get; set; }
    //bla bla bla
}
interface ITest3<iTest2>
{
    List<iTest2> manyTest { get; set; }
    //bla bla bla
}
class Test1 : ITest1<Test2, Test1>
{
    //bla bla bla
}
class Test2 : ITest2<Test1, Test3>
{
    //bla bla bla
}
class Test3 : ITest3<Test2>
{
    //bla bla bla    
}

Solution

  •  public abstract class MyBase
    {
        /// <summary>
        /// The my test method. divyang
        /// </summary>
        public virtual void MyVirtualMethodWhichIsOverridedInChild()
        {
            Console.Write("Method1 Call from MyBase");
        }
    
        /// <summary>
        /// The my another test method.
        /// </summary>
        public abstract void MyAnotherTestMethod();
    
        /// <summary>
        /// The my best method.
        /// </summary>
        public virtual void MyVirualMethodButNotOverridedInChild()
        {
            Console.Write("Method2 Call from MyBase");
        }
    }
    

    now make base class

    public abstract class CrtpBaseWrapper<T> : MyBase
        where T : CrtpBaseWrapper<T>
    {
    }
    

    then you can make your subclass

    public class CrtpChild : CrtpBaseWrapper<CrtpChild>
    {
        /// <summary>
        /// The my test method. divyang
        /// </summary>
        public override void MyVirtualMethodWhichIsOverridedInChild()
        {
            Console.Write("Method1 Call from CrtpChild");
        }
    
        /// <summary>
        /// The my another test method.
        /// </summary>
        public override void MyAnotherTestMethod()
        {
            Console.Write("MyAnotherTestMethod Call from CrtpChild");
        }
    }