views:

97

answers:

1

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?

+5  A: 

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.

Kirk Woll
Delegate[] del = theDelegate.GetInvocationList();for(int i = 0; i < del.Length; i++) {DelegateReturnsInt temp = (DelegateReturnsInt) del[i];}Yup, that works now. It was throwing Errors before, which was why I asked. Thanks for the explanation
Nicholas