Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when casting IEnumerable to ICollection

Given a case such that:

var collection = myEnumerable as ICollection<MyType>;

What happens under the hood? ICollection has a count property. Does this casting enumerate the enumerable to get the count or does something more involved happen?

like image 528
Jamie Dixon Avatar asked Dec 27 '22 17:12

Jamie Dixon


2 Answers

Nothing happens. If myEnumerable indeed is an ICollection<MyType> collection will contain it. Otherwise it will be null. Simple as that.

like image 158
Daniel Hilgarth Avatar answered Jan 15 '23 17:01

Daniel Hilgarth


Important point:

When ever you cast IEnumerable type object to ICollectionit will be referenced typed.

Like, removing Item from the collection will remove the item from the IEnumerable collection as well.

For Example:

IEnumerable<AnyClass> enumerableObject;

ICollection<AyClass> collectingObject = (ICollection<AnyClass>)enumerableObject;

foreach(var item in collectingObject){

collectingObject.Remove(item);

}

And if you access value of enumerableObject you will find it updated, with all the value removed.

like image 33
Khawaja Asim Avatar answered Jan 15 '23 17:01

Khawaja Asim