↓ Ir para o conteúdo principal

← todas as notas

📎 Webclip

Mastering C# Pattern Matching

The post takes Microsoft’s lock example and strips it down to the core idea of pattern matching in a C# switch expression. It models the gate as a state machine and shows how the gate’s next state depends on the requested setting, the current gate state, and the water level.

Reading notes
#

  • The example uses a gate and water level to model a lock.
  • The first three cases all end with the gate closed, so they can be grouped into one pattern.
  • When the new state is open and the water level is high, the gate opens.
  • When the new state is open and the water level is low, the code throws an exception.
  • The underscore matches anything, which makes the default case simpler.
  • The final method uses a switch expression instead of a longer set of if statements or switch statements.