Base de conhecimentoCentro de Exames
PT · PTPortuguês (Portugal)
Escolher idioma13

CKTIS / C#

pattern matching: referência prática

pattern matching: referência prática: Os padrões C# testam tipo, valor e estrutura e podem associar variáveis.

Versão: C# language and .NET 10 reference runtime

Sintaxe

// patterns

Os padrões C# testam tipo, valor e estrutura e podem associar variáveis.

Usa uma switch expression para mapear exaustivamente os casos.

A ordem dos braços importa; um padrão amplo anterior pode ocultar os seguintes.

null não corresponde a um padrão de tipo normal; se uma switch expression não exaustiva não tiver um braço aplicável, pode lançar SwitchExpressionException.

O programa completo usa realmente pattern matching; o stdout exato esperado é positive:7.

Exemplos

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;

object value = 7; var text = value switch { int number and > 0 => $"positive:{number}", null => "null", _ => "other" }; Console.WriteLine(text);

Resultado

positive:7

O programa completo usa realmente `pattern matching`; o stdout exato esperado é `positive:7`.

Fontes