Although C# remains an object-oriented programming language, it has incorporated more and more functional techniques over the years. One of this techniques is ‘pattern matching’.
On the Microsoft Learn website, it is explained like this:
Pattern matching is a technique where you test an expression to determine if it has certain characteristics.
Not so sexy right? In fact it is rather boring described like this. That is because pattern matching is not something fancy new. It is here to simplify complex if-else statements into more compact and readable code. Pattern matching does not aim at writing code that cannot be written without. Its only purpose is to have more concise and elegant code.
There are multiple supported pattern types; constant patterns, declaration patterns, relational patterns, and so on…
In this post I want to talk about a specific pattern; the type pattern.
The type pattern in itself is quite simple, it checks the runtime type of an expression. Here is a simple example in C#:
static void TypePattern(Shape shape) { | |
if (shape is Circle circle) | |
Console.WriteLine($"shape is a circle of radius {circle.Radius}"); | |
// Type pattern and compound expressions | |
if (shape is Rectangle rect && rect.Width == rect.Height) | |
Console.WriteLine($"shape is a square of length {rect.Width}"); | |
} |
A typical use case where I apply this is inside a CQRS or Actor model based system where a CommandHandler or Actor could handle multiple message types:
using System; | |
public interface ICommand{} | |
public record class CreateUserCommand(string Email, string Name):ICommand; | |
public record class DeleteUserCommand(string UserId):ICommand; | |
public static class UserCommandsHandler | |
{ | |
public static void Handle(ICommand command){ | |
switch(command){ | |
case CreateUserCommand createCommand: CreateUser(createCommand.Name,createCommand.Email); break; | |
case DeleteUserCommand deleteCommand: DeleteUser(deleteCommand.UserId);break; | |
default: throw new InvalidOperationException("Unknown command type"); | |
} | |
} | |
public static void CreateUser(string name, string email){} | |
public static void DeleteUser(string userId){} | |
} |
TypeScript also supports pattern matching, but you have to use a workaround when you want to use a type pattern. You cannot check the type itself but what you can do is add a type property on your object and combine this with a discriminated union:
interface Command { | |
type: string; | |
} | |
interface CreateUserCommand extends Command { | |
type: 'createUser'; | |
name: string; | |
email: string; | |
} | |
interface DeleteUserCommand extends Command { | |
type: 'deleteUser'; | |
userId: string; | |
} | |
export type UserCommand = | |
| CreateUserCommand | |
| DeleteUserCommand |
This type object can then be used inside your switch statement. The Typescript compiler will give you intellisense and detects the different types and their properties:
const handleUserCommands = (command: UserCommand) => { | |
switch (command.type) { | |
case 'createUser': | |
createUser(command.name, command.email); | |
break; | |
case 'deleteUser': | |
deleteUser(command.userId); | |
break; | |
default: | |
throw Error('Invalid command type'); | |
} | |
}; |