Search code examples
c#abstract-classinner-classesabstraction

Nested abstract class in an abstract class and how to implement it


I have an abstract class A and a abstract method with a parameter which is again abstract class B defined in the same abstract class A. When I extended this abstract class A as apart of another class C how can I implement the method with parameter of nested abstract class.

public abstract class A<T, V>
{
    public abstract int GetObject(T t, V v);
    public abstract int GetAnotherObject(B b);
    public abstract class B{}
}

This class is extended by another class C

public class C: A<ABC, DEF>
{
        public C()
        {

        }
        public override int GetObject(ABC abc, DEF def)
        {
            return 10;
        }

        public override int GetAnotherObject(B b)
        {
            return 15;
        }
}

How to implement class B with some properties and pass in GetAnotherObject method. Could someone please help me.


Solution

  • From ECMA:

    Any class nested inside a generic class declaration or a generic struct declaration (§25.2) is itself a generic class declaration, since type parameters for the containing type shall be supplied to create a constructed type.

    So, you cannot implement nested B without providing type arguments for A.

    void Main()
    {
        var c = new C();
        var result = c.GetAnotherObject(new BImpl<string, int>());
    }
    
    public class BImpl<T, V> : A<T, V>.B
    {
        public override int BM()
        {
            return 1;
        }
    }
    
    // Or you can supply type arguments right here
    //public class BImpl : A<string, int>.B
    //{
    //  public override int BM()
    //  {
    //      return 1;
    //  }
    //}
    
    public abstract class A<T, V>
    {
        public abstract int GetObject(T t, V v);
        public abstract int GetAnotherObject(B b);
        public abstract class B
        {
            public abstract int BM();
        }
    }
    
    public class C : A<string, int>
    {
        public C()
        {
    
        }
    
        public override int GetObject(string abc, int def)
        {
            return 10;
        }
    
        public override int GetAnotherObject(B b)
        {
            return b.BM();
        }
    }