Common constructors and inheritance

I have a generic class with a class constraint on it.

public class MyContainer<T> where T : MyBaseRow 

MyBaseRow is an abstract class that I also want to contain some flavor of MyContainer.

 public abstract class MyBaseRow { public MyContainer<MyBaseRow> ParentContainer; public MyBaseRow(MyContainer<MyBaseRow> parentContainer) { ParentContainer = parentContainer; } } 

I'm having problems with class constructors inherited from MyBaseRow, for example.

 public class MyInheritedRowA : MyBaseRow { public MyInheritedRowA(MyContainer<MyInheritedRowA> parentContainer) : base(parentContainer) { } } 

Will not allow MyInheritedRowA in the constructor, the compiler only expects and only resolves MyBaseRow. I thought a general class constraint allowed inheritance? What am I doing wrong here and is there a way to change these classes to get around this? Thanks a lot in advance for any answers.

+4
source share
2 answers

Basically, you cannot use generics in this way because the covariance system does not work with classes. See here: http://geekswithblogs.net/abhijeetp/archive/2010/01/10/covariance-and-contravariance-in-c-4.0.aspx

However, you can use this interface:

 public interface MyContainer<out T> where T : MyBaseRow { } 

And this code will be compiled.

+4
source

You can create a covariant common interface (C # 4.0):

  public interface IContainer<out T> where T : MyBaseRow { } public class MyContainer<T> : IContainer<T> where T : MyBaseRow { } public abstract class MyBaseRow { public IContainer<MyBaseRow> ParentContainer; public MyBaseRow(IContainer<MyBaseRow> parentContainer) { ParentContainer = parentContainer; } } public class MyInheritedRowA : MyBaseRow { public MyInheritedRowA(IContainer<MyInheritedRowA> parentContainer) : base(parentContainer) { } } 
+2
source

All Articles