How to apply foreach without explicit / implicit overrides?

So, I'm just learning C # and came across something that seems strange to me ... I play with delegates and create a DelegateReturnsInt delegate. Now, when I use the foreach loop , the book shows how to use it as follows:

foreach(DelegateReturnsInt del in theDelegate.getInvocationList()) 

I now know that getInvocationList () returns an Array of Delegate [], but how does it convert them to DelegateReturnsInt? I ask because I just wanted to play around and change it from 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 it does not see del [i] as a method. I tried casting for DelegateReturnsInt etc., but it gives me throw type errors in that they are not defined.

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

+6
casting c # foreach
source share
1 answer

He makes an implicit cast (if you look at the emitted IL, you will see it). It also means that you can get an unexpected casting exception on this line if that is not what you are saying.

+11
source share

All Articles