Introduction
Pattern matching helps your program understand and work with different types of data easily. It makes your code clearer and simpler by checking data shapes and values in one step.
Pattern matching helps your program understand and work with different types of data easily. It makes your code clearer and simpler by checking data shapes and values in one step.
public class PatternMatchingExample { public void CheckObject(object obj) { switch (obj) { case int number: Console.WriteLine($"It's an integer: {number}"); break; case string text: Console.WriteLine($"It's a string: {text}"); break; case null: Console.WriteLine("It's null"); break; default: Console.WriteLine("Unknown type"); break; } } }
object obj = 42; if (obj is int number) { Console.WriteLine($"Number is {number}"); }
object obj = "hello"; switch (obj) { case string text: Console.WriteLine($"Text is {text}"); break; default: Console.WriteLine("Not a string"); break; }
object obj = null; switch (obj) { case null: Console.WriteLine("Object is null"); break; default: Console.WriteLine("Object is not null"); break; }
using System; public class PatternMatchingExample { public void CheckObject(object obj) { switch (obj) { case int number: Console.WriteLine($"It's an integer: {number}"); break; case string text: Console.WriteLine($"It's a string: {text}"); break; case null: Console.WriteLine("It's null"); break; default: Console.WriteLine("Unknown type"); break; } } } public class Program { public static void Main() { PatternMatchingExample example = new PatternMatchingExample(); Console.WriteLine("Checking integer:"); example.CheckObject(100); Console.WriteLine("Checking string:"); example.CheckObject("hello world"); Console.WriteLine("Checking null:"); example.CheckObject(null); Console.WriteLine("Checking unknown type (double):"); example.CheckObject(3.14); } }
is in C#?is Type variable inside the if condition, like obj is int number.object obj = 42;
switch (obj)
{
case int i:
Console.WriteLine($"Integer: {i}");
break;
case string s:
Console.WriteLine($"String: {s}");
break;
default:
Console.WriteLine("Unknown type");
break;
}case int i because obj is an int, so it prints "Integer: 42".object obj = "hello";
if (obj is int number)
{
Console.WriteLine(number);
}obj is int number is false, so the block never runs.List<object> items = new() { 1, -2, "two", 3.0, null };, which pattern matching expression correctly counts only the positive integer values?Pass the test and this pattern moves unknown