Question

Im working with EntitFramework which generates my Entity classes:

I have these classes:

public class Car
{
    //...
    public String Brand { get; set; }
    //...

    public virtual ICollection<CarLocalized> CarLocalizeds { get; set; }
    //...
}

public class CarLocalized :ILocalized
{
    public int LangID { get; set; }

    public Lang Lang { get; set; }
}

public static class Helper {
    public static List<String> GetLangIDList(ICollection<ILocalized> list)
    {
        //I want all the ID of the lang where car is translated for:
        var somethin = list.Select(m => m.LCID_SpracheID.ToString()).ToList();
        return somethin;
    }
}

public class HomeController : Controller
{
    public ActionResult Translated()
    { 
        Car car = db.Cars.Find(2);
        List<String> transletedIDs = Helper.GetLangIDList(car.CarLocalizeds);

        return View(transletedIDs);
    }

}

but now the Problem is that

List<String> transletedIDs = Helper.GetLangIDList(car.CarLocalizeds);

is not working. Why can i not set the signature to ICollection and give it a ICollection where CarLocalized Implements the interface which is required in the Signature??

Please help me...

THx

Was it helpful?

Solution

Problem is ICollection<T> is not "Covariant". It seems GetLangIDList method doesn't modify the list, it just queries the list. In that case you can use IEnumerable<T> which is "Covariant".

public static List<String> GetLangIDList(IEnumerable<ILocalized> list)
{
    //I want all the ID of the lang where car is translated for:
    var somethin = list.Select(m => m.LCID_SpracheID.ToString()).ToList();
    return somethin;
}

Read more about Covariance and Contravariance in Generics and Faq

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top