Search code examples
c#genericsinheritanceinterfacecsla

How to solve generics error CS0311?


I have searched the web and stackoverflow and found many posts that deals with CS0311 error. None of the scenarios are close to mine. I have a generic class that inherits from a generic class.

Please note that BusinessBase is a class in the CSLA framework

What am I missing ?

public interface Itest
{
    int Digit();
}

class BB : Itest
{
    public int Digit()
    {
        return 20;
    }
}


class Test<T> : BusinessBase<T>, Itest where T : Test<T>, Itest
{
    public int Digit()
    {
        return 30;
    }
}

Test<Itest> test = new Test<Itest>(); //error CS0311

Error CS0311 The type 'MyTestApp.Itest' cannot be used as type parameter 'T' in the generic type or method 'A<T>'. There is no implicit reference conversion from 'MyTestApp.Itest' to 'MyTestApp.A<MyTestApp.Itest>'. MyTestApp


Solution

  • You can go something like this:

    interface Itest {}
    
    class BusinessBase<T> {
    
    }
    
    class Test<T> : BusinessBase<T>, Itest where T : Test<T>, Itest {
        public int Digit() {
            return 30;
        }
    }
    
    class IT : Test<IT>, Itest {
    
    }
    
    class Program {
        public static int Main() {
    
            var t = new Test<IT>();
            t.Digit();
            return 0;
        }
    }
    

    Which to me is a really awful use of generics, but that is how CSLA works....