Pattern Matching y Expresiones
Pattern matching en C# moderno transforma el código defensivo de "verificar tipo, hacer cast, verificar condición" en expresiones elegantes. Con is patterns: if (objeto is string s && s.Length > 0) en una sola línea verifica el tipo, lo convierte y pone condición. Las switch expressions con when permiten añadir condiciones a cada case.
El tuple pattern (a, b) switch { (true, true) => ... } maneja combinaciones de valores de forma muy declarativa.
Los property patterns son especialmente útiles con objetos: en lugar de if (punto.X > 0 && punto.Y > 0), escribes punto switch { { X: > 0, Y: > 0 } => "Primer cuadrante" }.
En C# 11 se añadieron list patterns para verificar arrays: nums is [1, 2, 3] verifica si el array tiene exactamente esos tres elementos en ese orden. Todos estos patrones hacen el código exhaustivo: el compilador te avisa si hay combinaciones que no están manejadas.
// is pattern
object obj = "Hola";
if (obj is string s) {
Console.WriteLine($"Es un string de largo {s.Length}");
}
// is con condición
if (obj is string texto && texto.Length > 3) {
Console.WriteLine("String largo");
}
// switch expression
string Clasificar(object o) => o switch {
int n when n < 0 => "Entero negativo",
int n when n == 0 => "Cero",
int n => $"Entero positivo: {n}",
string s when s.Length == 0 => "String vacío",
string s => $"String: {s}",
null => "Nulo",
_ => "Otro tipo"
};
Console.WriteLine(Clasificar(-5)); // Entero negativo
Console.WriteLine(Clasificar("Hi")); // String: Hi
Console.WriteLine(Clasificar(null)); // Nulo
// Tuple patterns
(bool estaLloviendo, bool hayViento) = (true, false);
string consejo = (estaLloviendo, hayViento) switch {
(true, true) => "Quédate en casa",
(true, false) => "Lleva paraguas",
(false, true) => "Lleva chaqueta",
(false, false) => "¡Buen día!"
};
// Property pattern
record Punto(int X, int Y);
var punto = new Punto(3, -2);
string cuadrante = punto switch {
{ X: > 0, Y: > 0 } => "Primer cuadrante",
{ X: < 0, Y: > 0 } => "Segundo cuadrante",
{ X: < 0, Y: < 0 } => "Tercer cuadrante",
{ X: > 0, Y: < 0 } => "Cuarto cuadrante",
_ => "En el eje"
};
// List pattern (C# 11)
int[] nums = { 1, 2, 3 };
bool esEste = nums is [1, 2, 3]; // true
Practica esta lección
Resuelve los ejercicios del curso de C# en la app, gratis y con corrección automática.
Empezar a practicar