Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does foreach cast without explicit/implicit overrides?

So I'm just learning C#, and came across something that I find odd... I'm playing with delegates and have creates a delegate DelegateReturnsInt. Now, When I use a foreach loop, the book shows to use it like this:

foreach(DelegateReturnsInt del in theDelegate.getInvocationList())

now I know that getInvocationList() returns an Array of Delegate[], but how does it convert them to DelegateReturnsInt? I ask because I wanted to just play around and change it from a foreach to a for loop, so I created this

Delegate[] del = theDelegate.GetInvocationList();
for(int i = 0; i < del.Length; i++){
    int result = del[i]();

but that doesn't see del[i] as a method. I've tried casting to DelegateReturnsInt and such, but it gives me cast type errors about not having it defined.

My big question is what makes foreach() so special?

like image 726
Nicholas Avatar asked Aug 12 '10 20:08

Nicholas


1 Answers

It does an implicit cast (if you look at the emitted IL, you'd see it). This also means you could get an unexpected cast exception on that line if it's not what you say it is.

like image 133
Kirk Woll Avatar answered Sep 23 '22 04:09

Kirk Woll