This is my set up,
class CostPeriodDto : IPeriodCalculation
{
public decimal? a { get; set; }
public decimal? b { get; set; }
public decimal? c { get; set; }
public decimal? d { get; set; }
}
interface IPeriodCalculation
{
decimal? a { get; set; }
decimal? b { get; set; }
}
class myDto
{
public List<CostPeriodDto> costPeriodList{ get; set; }
public List<IPeriodCalculation> periodCalcList
{
get
{
return this.costPeriodList; // compile error
}
}
}
What would be the best way of doing this?
Use Cast<IPeriodCalculation>()
:
public class CostPeriodDto : IPeriodCalculation
{
public decimal? a { get; set; }
public decimal? b { get; set; }
public decimal? c { get; set; }
public decimal? d { get; set; }
}
public interface IPeriodCalculation
{
decimal? a { get; set; }
decimal? b { get; set; }
}
public class myDto
{
public List<CostPeriodDto> costPeriodList { get; set; }
public List<IPeriodCalculation> periodCalcList
{
get
{
return this.costPeriodList.Cast<IPeriodCalculation>().ToList();
}
}
}
I believe in C#4, if you were using something implementing IEnumerable<out T>
, you could simply do it the way you wrote it, and it would be resolved using Covariance.
class myDto
{
public IEnumerable<CostPeriodDto> costPeriodList{ get; set; }
public IEnumerable<IPeriodCalculation> periodCalcList
{
get
{
return this.costPeriodList; // wont give a compilation error
}
}
}
Try return this.costPeriodList.Cast<IPeriodCalculation>().ToList()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With