C# "yield break" the way to go?

Hi friends,

I’m converting a file from Javascript to C# and I came across a plain yield statement in J. Is the ‘yield break’ statement in C# comparable?

Thanks as always!

yield return;

Edit: also, coroutines have a different syntax in C# and have to have IEnumerator as the return type.

It’s explained in the script ref, under “Using C#”.

Just in case you didn’t know :wink:

-Jeremy

I was still curious about what what yield break does and how it differs from yield return, so I spent another while reading other C# blogs and such and I think I’ve got it- let me see if I can explain it for others like myself; Correct me if I’m wrong gurus =):

A class that extends IEnumerator is fundamentally a class which maintains the state or current position of where we are in a list of items (Called an iterator block). Each time we hit a ‘yield return value’ in our IEnumerator class, execution of that function pauses. The next time the function is called, the function resumes from the point we paused at. ‘yield break’ is like the reset button. It exits the function and makes it so that we start from the beginning of the function the next time it’s called.

Most of the time, when we use a yield return instruction in Unity, we are doing so from within a function that returns an IEnumerator within a class that extends MonoBehavior, and we’re using the yield return to say “come back to this later and pick up from here”. Since yield break tells the program to start from the beginning of the function, it isn’t frequently useful in Unity (since starting at the beginning of a function is the default behavior of non-enumerator functions anyway).

Hope this trivia is enlightening =)

9 Likes

JavaScript → C#

yield; → yield return 0;
return; → yield break;
yield WaitForSeconds(1.5); → yield return new WaitForSeconds(1.5f);

6 Likes

Thanks =)