Sunday, June 1, 2014

Instantiating an ICollection of some interface objects: Compiler Error

My code:



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CarOwnership
{
public interface ICar
{
string Make { get; set; }
string Model { get; set; }
}
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<ICar> CarsOwned { get; set; }

public Person()
{
//This assignment gives a compiler error:
//Cannot implicitly convert type
//'System.Collections.Generic.List<CarOwnership.VintageCar>' to
//'System.Collections.Generic.ICollection<CarOwnership.ICar>'.
//An explicit conversion exists (are you missing a cast?)

this.CarsOwned = new List<VintageCar>();
}
}

public class VintageCar : ICar
{
public int Id { get; set; }
public string Make { get; set; }
public string Model { get; set; }
public decimal Cost { get; set; }
public string Remarks { get; set; }
}
}



Why does the assignment



this.CarsOwned = new List<VintageCar>();

gives the compiler error?


Is an explicit cast the only way out?


No comments:

Post a Comment