New Message on dotNET User Group Hyd

foreach Surprise????

Reply
  Reply to Sender   Recommend Message 3 in Discussion
From: Anand Kumar

Hi Folks,

Here is the answer ,remember that a foreach loop is used to iterate over collection types. This is achieved by retrieving an enumerator and using its MoveNext operation to continually walk the list and its Current property to retrieve the current item from the list. The enumerator is retrieved using the collection's GetEnumerator method. Since this enumerator might implement IDisposable, the C# compiler needs to ensure that it is disposed as soon as the iteration has completed. As a result, it generates the loop in a try block and then attempts to dispose of the enumerator in the finally block. If the return type of the GetEnumerator method is one that implements IDisposable, the compiler will generate a finally block containing code similar to this:

((IDisposable)enumerator).Dispose();

However, if the enumerator type returned does not implement IDisposable, the compiler still has to attempt to dispose the object since it can't be sure that a derived type (which can be returned from the function) doesn't implement IDisposable. Consequently, the compiler will generate a finally block containing several lines of code similar to the following:

IDisposable disposable = enumerator as IDisposable;
if (disposable != null) disposable.Dispose();

Since most enumerable classes have a GetEnumerator method that returns IEnumerator (which does not implement IDisposable), due to this my sample code IL has the try and catch blcok .

Cheers
anand
http://spaces.msn.com/members/anandkumar


View other groups in this category.

Click here
Also on MSN:
Start Chatting | Listen to Music | House & Home | Try Online Dating | Daily Horoscopes

To stop getting this e-mail, or change how often it arrives, go to your E-mail Settings.

Need help? If you've forgotten your password, please go to Passport Member Services.
For other questions or feedback, go to our Contact Us page.

If you do not want to receive future e-mail from this MSN group, or if you received this message by mistake, please click the "Remove" link below. On the pre-addressed e-mail message that opens, simply click "Send". Your e-mail address will be deleted from this group's mailing list.
Remove my e-mail address from dotNET User Group Hyd.

Reply via email to