Pattern Matching: Patterns are introduced in 7.0.
We can perform Pattern on
Any Data Type.
We can also extract a
value from an expression.
We can do Pattern matching
in Two Cases which is useful for us.
Using the is expression.
Using
the switch
statement.
Using is expression:
‘is’ Pattern
Matching
Using this we can assign
to a variable.
Before C#7.0
class Program
{
public void GetDetails(dynamic a)
{
if (a is Employee) {
var c = a as Employee;
Console.WriteLine(c.Empid);
}
else if (a is Student) {
var c = a as Student;
Console.WriteLine(c.StudentId);
Console.ReadLine();
}
}
static void Main(string[] args) {
dynamic a = new Student();
a.StudentId = 1;
Program obj = new Program();
obj.GetDetails(a);
}
}
class Employee {
public int Empid { get; set; }
}
class Student{
public int StudentId { get; set; }
}
Output:
After C# 7.0
class Program
{
public void GetDetails(dynamic a)
{
if (a is Employee emp)
Console.WriteLine(emp.Empid);
if (a is Student student)
Console.WriteLine(student.StudentId);
Console.ReadLine();
}
static void Main(string[] args) {
dynamic a = new Student();
a.StudentId = 1;
Program obj = new Program();
obj.GetDetails(a);
}
}
class Employee {
public int Empid { get; set; }
}
class Student{
public int StudentId { get; set; }
}
Using the switch statement.
class Program
{
public void GetDetails(dynamic a)
{
switch (a)
{
case Employee
emp:
Console.WriteLine(emp.Empid);
Console.ReadLine();
break;
case Student
student:
Console.WriteLine(student.StudentId);
Console.ReadLine();
break;
}
}
static void Main(string[] args) {
dynamic a = new Student();
a.StudentId = 1;
Program obj = new Program();
obj.GetDetails(a);
}
}
class Employee {
public int Empid { get; set; }
}
class Student{
public int StudentId { get; set; }
}
Switch Statement with
When Condition
class Program
{
public void GetDetails(dynamic a)
{
switch (a)
{
case Employee emp:
Console.WriteLine(emp.Empid);
Console.ReadLine();
break;
case Student student when student.StudentId==1:
Console.WriteLine(student.StudentId);
Console.ReadLine();
break;
case Student student when student.StudentId ==
2:
Console.WriteLine(student.StudentId);
Console.ReadLine();
break;
case Student student when student.StudentId ==
3:
Console.WriteLine(student.StudentId);
Console.ReadLine();
break;
}
}
static void Main(string[] args) {
dynamic a = new Student();
a.StudentId = 3;
Program obj = new Program();
obj.GetDetails(a);
}
}
class Employee {
public int Empid { get; set; }
}
class Student{
public int StudentId { get; set; }
}
Output:
No comments:
Post a Comment
Thank you for visiting my blog