Search code examples
c#classgenericsabstractprotected

Protected generic class - is it supported?


I had a question on C# generics. I wish to store a generic type variable in my abstract class without declaring that type outside the class.

Below is the code sample. Please note that I do not wish to make the Param classes exposed outside the Calc class.

Thanks in advance. - Dutta.

abstract class Base { }

abstract class Calc<T> where T : Base
{
    protected Param Member; /* how can this be a made a generic declaration 
                             * WITHOUT declaring this class like,
                             * class Calc<T, P> 
                             *      where T : Base
                             *      where P : Param */

    protected Calc(Param p)
    {
        this.Member = p;
    }

    protected abstract class Param { }
}

class MyBase : Base { }

class MyCalc : Calc<MyBase>
{
    public MyCalc() : base(new MyParam()) { }

    public void doSomething()
    {
        base.Member.A++; // fails on compilation
    }

    private class MyParam : Calc<MyBase>.Param
    {
        public int A;

        public MyParam() { this.A = 0; }
    }
}

Solution

  • You just need to cast it to the new type, because no matter what, the variable Member was declared as Param and it will always be accessed as Param:

    ((MyParam)base.Member).A++; 
    

    Secondly, you can fix up your MyParam class by changing from this:

    MyParam : Calc<MyBase>.Param
    

    To this:

    MyParam : Param
    

    Because Param is already Calc<MyBase> through generics and inheritance.