0

I have an abstract data entity MyDataRow which inheritance DataRowA from it. There is a generic class which use of it BusinessRow<TData> where TData:MyDataRow. Problem is where I want create a new object of BusinessRow depend of a string variable:
public BusinessRow<MyDataRow> AddNewRow(string rowType)
and using one of the inheritance class of MyDataRow in its generic type:

public class BusinessRow<TData>
    where TData : MyDataRow
{
}

public abstract class MyDataRow
{
}

public class DataRowA : MyDataRow
{
}

public class Main
{
    public BusinessRow<MyDataRow> AddNewRow(string rowType)
    {
        BusinessRow<MyDataRow> row = null;
        switch (rowType)
        {
            case "A":
            default:

                row =new BusinessRow<DataRowA>();
// Error CS0029  Cannot implicitly convert type 
// 'BusinessRow<DataRowA>' to 'BusinessRow<MyDataRow>' 

                break;
        }
        return row;
    }
}

at the following code

BusinessRow<MyDataRow> row = new BusinessRow<DataRowA>();

I get this error

Error CS0029  Cannot implicitly convert type 
 'BusinessRow<DataRowA>' to 'BusinessRow<MyDataRow>'
Hamid
  • 817
  • 1
  • 13
  • 29
  • 2
    Just because `DataRowA : DataRow`, doesn't mean `T : T`. Your constraint must be *co-variant*, and you must define it on an interface. – Rob May 14 '16 at 08:06
  • See [here](http://stackoverflow.com/questions/1962629/contravariance-explained) – Rob May 14 '16 at 08:07
  • You cannot call the constructor to a DataRow. The DataRow gets it properties from the parent DataTable. So a new row is usually obtained from DataRow dr = dt.Rows.Add(). It your code you do not need 'new'. – jdweng May 14 '16 at 08:08
  • @jdweng They are not creating an instance of `DataRow`. And even if they were, they are using their own class named `DataRow`, not part of the standard library. – Rob May 14 '16 at 08:16
  • Please don't think about System.Data.DataRow or DataTable because I didn't use of System.Data namespace. DataRow is my personal class – Hamid May 14 '16 at 10:50
  • @Rob, But interface does not help. Do you have any solution? – Hamid May 14 '16 at 10:54
  • @Hamid You'll need to create an interface and define it like `interface IDataRow where TRowType : MyDataRow` and then implement it: `class BusinessRow : IDataRow where TRowType : MyDataRow`, and then return `IBusinessRow` instead of `BusinessRow`, but you should read up on covariance tutorials / explanations. – Rob May 14 '16 at 11:01
  • It's a bit complicated! – Hamid May 14 '16 at 11:38

0 Answers0