C
C#10mo ago
Raki

Reading MSDN document what does this mean while reading local function

One of the useful features of local functions is that they can allow exceptions to surface immediately. For iterator methods, exceptions are surfaced only when the returned sequence is enumerated, and not when the iterator is retrieved. For async methods, any exceptions thrown in an async method are observed when the returned task is awaited.
I can understand with async method so while returning async only we will come to know about exceptions. Just for understanding so For iterator methods, exceptions are surfaced only when the returned sequence is enumerated, So this means when we enumerate like the collection is read like using for loop. But what this means and not when the iterator is retrieved
1 Reply
Gramore
Gramore10mo ago
You can access an iterator without enumerating it:
// Our collection
string[] people = ["Fred","Bob","Randy"]
// Retreiving the iterator, but not enumerating it
IEnumerator<string> iterator = people.GetEnumerator();
// Enumerating the collection
foreach (string person in people)
{}
// Enumerating the collection
List<string> peopleList = people.ToList();
// Our collection
string[] people = ["Fred","Bob","Randy"]
// Retreiving the iterator, but not enumerating it
IEnumerator<string> iterator = people.GetEnumerator();
// Enumerating the collection
foreach (string person in people)
{}
// Enumerating the collection
List<string> peopleList = people.ToList();
For an example with exceptions:
IEnumerable<string> peopleMapped = people.Select(s =>
{
if (s == "Bob") throw new InvalidOperationException("We don't like Bob");
return s;
});
// Still no exception
IEnumerator<string> iterator = peopleMapped.GetEnumerator();
// Now we'll blow up.
List<string> filteredPeople = peopleMapped.ToList();
IEnumerable<string> peopleMapped = people.Select(s =>
{
if (s == "Bob") throw new InvalidOperationException("We don't like Bob");
return s;
});
// Still no exception
IEnumerator<string> iterator = peopleMapped.GetEnumerator();
// Now we'll blow up.
List<string> filteredPeople = peopleMapped.ToList();
ofc this skips actually using iterator since it's pretty unlikely that you'd actually manually operate the IEnumerator
Want results from more Discord servers?
Add your server