0

I have a method taking a parameter EntityCollection

Say:

DisplayItems(EntityCollection<Object> items);

Why is it not possible to call?

EntityCollection<Student> students;

DisplayItems((EntityCollection<Object>) students); //type casting here

How can I achieve this?

Please help

Gautam Jain
  • 6,789
  • 10
  • 48
  • 67

2 Answers2

1

Your problem occurs because of Covariance and Contravariance, imagine that worked as you want it to, you could then do this :

public void DisplayItems(EntityCollection<Object> items)
{
        //Probably not called add but you get the idea...
        items.Add(new AnyObjectILike());
        items.Add(new System.Windows.Form());
}

EntityCollection<Student> students;  
DisplayItems((EntityCollection<Object>)  students); //type casting here 

Clearly adding instances that are not of type Student to the EntityCollection<Student> causes a massive problem which is one of the reasons this is not allowed, you can alter this behaviour for interfaces using the In and Out keywords.

Richard Friend
  • 15,800
  • 1
  • 42
  • 60
-2

Similar answer can be found here:

convert or cast a List<t> to EntityCollection<T>

You need to loop and cast each element individually, adding them to a new EntityCollection.

Another option would be to use the Cast() method, but I'm not sure that will work with an EntityCollection. It works with a List:

List<Object> myItems = students.Cast<Object>().ToList();

I'm unable to check this would work with an EntityCollection but worth a try?

Community
  • 1
  • 1
Tomas McGuinness
  • 7,651
  • 3
  • 28
  • 40
  • No, this is not about casting `List<>` to `EntityCollection<>` - this is about contra/co-variance between `EntityCollection` and `EntityCollection`. Different kettle of fish entirely! – Dan Puzey Apr 08 '11 at 10:38
  • I understand, but the principal is the same. Typed lists cannot be easily casted from one to the other - generally it's done one element at a time. – Tomas McGuinness Apr 08 '11 at 10:41