Search code examples
c#genericssubclass

C# subclassing with generics: I need an extra generic parameter for ctor, but how?


I have a class

public class LDBList<T> : List<T> where T : LDBRootClass {
    // typical constructor
    public LDBList(LDBList<T> x) : base(x) { }
    ...
}

but I want to have an extra constructor that takes a list of a different generic type (say A), and a function that converts an A to a T, and build the T list from that, something like

public LDBList(
        Func<A, T> converter, 
        IList<A> aList)
{
    foreach (var x in aList) {
        this.Append(converter(x));
    }
}

so converter is of type A->T so I take an A list and make a T list from it. My class is parameterised by T so that's fine.

But it's complaining "The type or namespace name 'A' could not be found".

OK, so it needs the an A generic parameter on the class I suppose (it really doesn't like it on the constructor). But where do I put it, in fact is this even possible?


Solution

  • I don't believe you can add additional generic types to a constructor like that that.

    I would refactor the converter to do the creation and return the instance of LDBList, that way the convert acts as a factory for creating LDBLists from instances of A.

    public class Converter<T,A>
    {
        public LDbList<T> CreateLdbList(IList<A>) {
           var list = new LdbList<T>();
           // do the conversion here
           return list;
        }
    }
    

    then, change the usage to be

    var Converter<X,Y> = new Converter();
    var result = Converter.Convert(originalData);