8

This is weird, I'm trying to initalize my ICollection with List in my constructor and this happens:

Schedules = new List<BookingSchedule>(); //OK
CateringItems = new List<CateringItem>(); //Not

The properties:

public virtual ICollection<BookingSchedule> Schedules { get; set; }
public virtual ICollection<BookedCateringItem> CateringItems { get; set; }

Error:

Error   1   Cannot implicitly convert type
'System.Collections.Generic.List<MyApp.Models.CateringItem>' to  
'System.Collections.Generic.ICollection<MyApp.Models.BookedCateringItem>'. 
An explicit conversion exists (are you missing a cast?)

I can't see the difference between the two. I'm going insane trying to figure this out. Any idea?

kazinix
  • 28,987
  • 33
  • 107
  • 157

4 Answers4

19

You can only convert List<T1> to ICollection<T2> if the types T1 and T2 are the same. Alternatively, you can convert to the non-generic ICollection

ICollection CateringItems = new List<CateringItem>(); // OK
helb
  • 7,609
  • 8
  • 36
  • 58
  • Done. And +1 for the extra suggestion about the non-generic `ICollection`, which in certain circumstances (WPF view-models) can be desirable. – O. R. Mapper Jan 10 '14 at 12:25
4
    public virtual ICollection<BookedCateringItem> CateringItems { get; set; }
    CateringItems = new List<CateringItem>();

It's different types, BookedCateringItem and CateringItem. You need to change one of them to be the other type.

EMB
  • 171
  • 1
  • 7
3

your CateringItems is a collection of BookedCateringItem, while initializing, you initialized a list of CateringItem.

apparently they are not compatible...

Lloyd
  • 29,197
  • 4
  • 84
  • 98
Rex
  • 2,130
  • 11
  • 12
0

You want assign List<CateringItem> to ICollection<BookedCateringItem> So you can not.