I already posted this question with a bad sample.
This code should be better.
To avoid confusion I summarised some code:
using System.Collections.Generic;
namespace ConsoleApplication1
{
class Program
{
static void Main()
{
IManager<ISpecificEntity> specificManager = new SpecificEntityManager();
IManager<IAntoherSpecificEntity> anotherSpecificManager = new AnotherSpecificEntityManager();
Dictionary<string, IManager<IIdentifier>> managers = new Dictionary<string, IManager<IIdentifier>>();
managers.Add("SpecificManager", (IManager<IIdentifier>)specificManager);
managers.Add("AnotherSpecificManager", (IManager<IIdentifier>)anotherSpecificManager);
foreach (var manager in managers.Values)
{
IIdentifier entity = manager.Container.GetEntity();
}
}
}
internal interface IIdentifier
{
int Id { get; set; }
}
internal interface ISpecificEntity : IIdentifier
{
string SpecificValue { get; set; }
}
internal class SpecificEntity : ISpecificEntity
{
public int Id { get; set; }
public string SpecificValue { get; set; }
}
internal interface IAntoherSpecificEntity : IIdentifier
{
string AnotherSpecificValue { get; set; }
}
internal class AntoherSpecificEntity : IAntoherSpecificEntity
{
public int Id { get; set; }
public string AnotherSpecificValue { get; set; }
}
internal interface IContainer<out TIdentifier> where TIdentifier : IIdentifier
{
TIdentifier GetEntity();
}
internal interface ISpecificContainer : IContainer<ISpecificEntity>
{
}
internal class SpecificContainer : ISpecificContainer
{
public ISpecificEntity GetEntity()
{
return new SpecificEntity { SpecificValue = "SpecificValue" };
}
}
internal interface IAnotherSpecificContainer : IContainer<IAntoherSpecificEntity>
{
}
internal class AnotherSpecificContainer : IAnotherSpecificContainer
{
public IAntoherSpecificEntity GetEntity()
{
return new AntoherSpecificEntity { AnotherSpecificValue = "AnotherSpecificValue" };
}
}
internal interface IManager<TIdentifier> where TIdentifier : IIdentifier
{
IContainer<TIdentifier> Container { get; set; }
}
internal class SpecificEntityManager : IManager<ISpecificEntity>
{
public IContainer<ISpecificEntity> Container { get; set; }
}
internal class AnotherSpecificEntityManager : IManager<IAntoherSpecificEntity>
{
public IContainer<IAntoherSpecificEntity> Container { get; set; }
}
}
When I debug the code I get an InvalidCastException in Main()
in line 12.
I know that ISpecificEntity
implements IIdentifier
.
But obviously a direct cast from an IManager<ISpecificEntity>
into an IManager<IIdentifier>
does not work.
I thought working with covariance could do the trick but changing IManager<TIdentifier>
into IManager<in TIdentifier>
or IManager<out TIdentifier>
does not work either.
So, is there a way do cast specificManager
into an IManager<IIdentifier>
?
Thanks and all the best.