implementing a state machine using the “yield” keyword

It’s feasible but it is a bad idea. Iterator blocks were created to help you write custom iterators for collections, not for solving the general-purpose problem of implementing state machines.

If you want to write a state machine, just write a state machine. It’s not hard. If you want to write a lot of state machines, write a library of useful helper methods that let you cleanly represent state machines, and then use your library. But don’t abuse a language construct intended for something completely different that just happens to use state machines as an implementation detail. That makes your state machine code hard to read, understand, debug, maintain and extend.

(And incidentally, I did a double-take when reading your name. One of the designers of C# is also named Matt Warren!)

Leave a Comment