kazinix
kazinix

Reputation: 30163

C# List to ICollection

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?

Upvotes: 8

Views: 41271

Answers (4)

Rex
Rex

Reputation: 2140

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

apparently they are not compatible...

Upvotes: 3

helb
helb

Reputation: 7793

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

Upvotes: 19

user1968030
user1968030

Reputation:

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

Upvotes: 0

EMB
EMB

Reputation: 171

    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.

Upvotes: 4

Related Questions