C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
C# Pattern MatchingC# pattern matching is a feature that allows us to perform matching on data or any object. We can perform pattern matching using the is expression and switch statement. is expression is used to check, whether an object is compatible with given type or not. In the following example, we are implementing is expression. C# Pattern Matching using is Exampleusing System; namespace CSharpFeatures { class Student { public string Name { get; set; } = "Rahul kumar"; } class PatternMatchingExample { public static void Main(string[] args) { Student student = new Student(); if(student is Student) { Console.WriteLine(student.Name); } } } } Output: Rahul kumar We can also perform pattern matching in switch statement. See, the following example. C# Pattern in Switch Case Example 2using System; namespace CSharpFeatures { class Student { public string Name { get; set; } = "Rahul kumar"; } class Teacher { public string Name { get; set; } = "Peter"; public string Specialization { get; set; } = "Computer Science"; } class PatternMatchingExample { public static void Main(string[] args) { Student student = new Student(); Teacher teacher = new Teacher(); PatterInSwitch(student); PatterInSwitch(teacher); } public static void PatterInSwitch(object obj) { switch (obj) { case Student student: Console.WriteLine(student.Name); break; case Teacher teacher: Console.WriteLine(teacher.Name); Console.WriteLine(teacher.Specialization); break; default: throw new ArgumentException( message: "Oject is not recognized", paramName: nameof(obj)); } } } } Output: Rahul kumar Peter Computer Science
Next TopicC# Tuples
|