Base de conocimientosCentro de exámenes
ESEspañol
Elegir idioma13

CKTIS / C#

switch: referencia práctica

switch: referencia práctica: switch elige el primer case o brazo de patrón coincidente.

Versión: C# language; verified against C# 14 reference

Sintaxis

switch /* grammar-specific form */

switch elige el primer case o brazo de patrón coincidente.

Úsalo para variantes cerradas y una descomposición clara de los datos.

El orden de patrones importa, pues un caso amplio puede ocultar uno más estrecho.

Una switch expression sin brazo coincidente puede lanzar SwitchExpressionException.

El programa completo usa realmente switch; su stdout esperado exacto es two.

Ejemplos

using System;
using System.Buffers;
using System.Collections.Concurrent;
using System.Collections.Frozen;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using Number = System.Int32;

var value = 2; Console.WriteLine(value switch { 1 => "one", 2 => "two", _ => "other" });

Resultado

two

El programa completo usa realmente `switch`; su stdout esperado exacto es `two`.

Fuentes