Question

I am converting a C# project into VB.net and need to understand C#'s Yield Break. I know there are already questions concerning Yield Break on Stack Overflow, but I feel these questions are a little different.

1.) When you Yield Break does the function that contains it return a value to the caller? If so, is it Null/Nothing, the default value for the type that the function is, or something else?

2.) When you Yield Break does the Iterator start over. In other words, the next time the Iterator is called, will it return the first item in the collection again?

3.) What is the closest vb.net equivalent to Yield Break? Exit Function? Return Nothing? Something Else?

Was it helpful?

Solution

  1. When you Yield Break does the function that contains it return a value to the caller? If so, is it Null/Nothing, the default value for the type that the function is, or something else?

No, it does not return a value. It just ends the enumeration. You can say, that it sets IEnumerator.MoveNext() return value to false and that's it.

  1. When you Yield Break does the Iterator start over. In other words, the next time the Iterator is called, will it return the first item in the collection again?

It all depends on how your method is written, but when you call the method which uses yield you're creating new instance of state machine, so it can return the same values again.

  1. What is the closest vb.net equivalent to Yield Break? Exit Function? Return Nothing? Something Else?

"You can use an Exit Function or Return statement to end the iteration."

from Yield Statement (Visual Basic)

OTHER TIPS

yield break; does not yield an item as part of the IEnumerable<T> return value.

For example, the following gives you an empty enumerable:

IEnumerable<int> F()
{
     yield break;
}

This means F().Count() is 0.

When you Yield Break does the function that contains it return a value to the caller? If so, is it Null/Nothing, the default value for the type that the function is, or something else?

No, it stops the generation. No value is produced by yield break;. If you think of the iterator as a loop with a callback, it’s like breaking out of the loop.

When you Yield Break does the Iterator start over. In other words, the next time the Iterator is called, will it return the first item in the collection again?

Yep, it’s called again, it produces a new iterator.

What is the closest vb.net equivalent to Yield Break? Exit Function? Return Nothing? Something Else?

Exit Function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top