Skip to content

Instantly share code, notes, and snippets.

@nasser
Last active April 14, 2021 18:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nasser/c0f97476aefe4de7765bc17d10a043ab to your computer and use it in GitHub Desktop.
Save nasser/c0f97476aefe4de7765bc17d10a043ab to your computer and use it in GitHub Desktop.
sketching yield* in c#
// coroutines in c#/unity are missing something like javascript's yield* which both wait for another
// coroutine *and* returns a value when that coroutine is finished.
// i think we can reproduce it with roslyn source transformations or something similar
// the trick is a WaitFor static method that allows the type inference to line up
// the method is never meant to actually be called though, and will throw if it ever is
// instead calls to the method are replaced with a local variable store, a yield return, and a field access
public class Coroutines {
public static T WaitFor<T>(IEnumerator<T> ie) {
throw new NotImplementedException();
}
public static object WaitFor(IEnumerator ie) {
throw new NotImplementedException();
}
// dummy coroutine
public IEnumerator M() {
yield return 1;
yield return 2;
yield return 3;
}
// dummy coroutine
public IEnumerator<int> M1() {
yield return 1;
yield return 2;
yield return 3;
}
public IEnumerator Usage() {
// source (ideal)
// var local = yield* M();
// source (actual)
var local = WaitFor(M1());
// the call to WaitFor becomes the following,
// storing _m.Current (the last value yielded) into local
var _m = M();
yield return _m;
var local = _m.Current;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment