I'm experiencing an unexpected issue.
I would like to cast a child class with a special type to its parent class with a generic type but the compiler does not want this to happen...
Here is my parent class:
public abstract class DataSource<T>
{
// Abstract methods and constructor
}
One of the child classes:
public class XlsxDataSource : DataSource<Row>
{
// Overriden methods and constructor
}
And the code giving the error:
XlsxDataSource dataSource = new XlsxDataSource();
var dataSources = new Dictionary<long, DataSource<Object>>();
dataSources[dataSource.id] = (DataSource<Object>) dataSource;
As you can see, I have a Dictionary that can contain many DataSources regardless of the child type.
But the last line is giving the next compile error:
Cannot convert type 'EDS.Models.XlsxDataSource' to 'EDS.Models.DataSource'
And I don't get why, as XlsxDataSource is a child from DataSource and the type in XlsxDataSource is explicitly Row which is obviously implementing System.Object.
Edit
The co-variant interface is not working in my case.
Here is my modified code:
public interface IDataSource<T, in T1>
{
List<T> GetAllRows();
List<Object> GetValues(T1 row);
}
The abstract class:
public abstract class DataSource<T, T1> : IDataSource<T, T1>
{
public abstract List<T> GetAllRows();
public abstract List<Object> GetValues(T1 row);
}
And finally the less derived class:
public class XlsxDataSource : DataSource<Row, Row>, IDataSource<Row, Row>
{
public abstract List<Row> GetAllRows();
public abstract List<Object> GetValues(Row row);
}
Here is the casting:
IDataSource<Object, Object> datasource = (IDataSource<Object, Object>) new XlsxDataSource();
But casting an XlsxDataSource to an IDataSource object is resulting in an InvalidCastException:
Unable to cast object of type 'EDS.Models.XlsxDataSource' to type 'EDS.Models.IDataSource`2[System.Object,System.Object]'.
DataSource<Object>, it's aDataSource<Row>. If you want co-variance you'll have to work with interfaces instead of classes.DataSourceclass so there is no redundant code, wich is impossible with an interface.XlsxDataSourceobject to aDictionarythat only acceptDataSource<Object>objects... When I try, here is the error that I get:Cannot implicitly convert type 'EDS.Models.XlsxDataSource' to 'EDS.Models.DataSource<object>'