This content originally appeared on DEV Community and was authored by Russell Nguyen
Pattern Matching is an important feature from C# 7.
Here is an example to show how i can be used.
internal class Program
{
static void Main(string[] args)
{
Rectangle rectangle = new Rectangle(5.0, 5.0);
Circle circle = new Circle(5.0);
Square square = new Square(5.0);
var a1 = Area(rectangle);
var a2 = Area(circle);
var a3 = Area(square);
}
public static double Area (object shape)
{
if (shape is Rectangle r) return r.Width * r.Height;
if (shape is Circle c) return c.Radius*2*Math.PI;
if (shape is Square s) return s.Length*s.Length;
return double.NaN;
}
}
public class Rectangle
{
public double Width { get; set; }
public double Height { get; set; }
public Rectangle(double width, double height)
{
Width = width;
Height = height;
}
}
public class Circle
{
public double Radius { get; set; }
public Circle(double radius)
{
Radius = radius;
}
}
public class Square
{
public double Length { get; set; }
public Square(double length)
{
Length = length;
}
}
This content originally appeared on DEV Community and was authored by Russell Nguyen
Print
Share
Comment
Cite
Upload
Translate
Updates
There are no updates yet.
Click the Upload button above to add an update.

APA
MLA
Russell Nguyen | Sciencx (2024-10-06T00:48:26+00:00) Pattern Matching. Retrieved from https://www.scien.cx/2024/10/06/pattern-matching/
" » Pattern Matching." Russell Nguyen | Sciencx - Sunday October 6, 2024, https://www.scien.cx/2024/10/06/pattern-matching/
HARVARDRussell Nguyen | Sciencx Sunday October 6, 2024 » Pattern Matching., viewed ,<https://www.scien.cx/2024/10/06/pattern-matching/>
VANCOUVERRussell Nguyen | Sciencx - » Pattern Matching. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/10/06/pattern-matching/
CHICAGO" » Pattern Matching." Russell Nguyen | Sciencx - Accessed . https://www.scien.cx/2024/10/06/pattern-matching/
IEEE" » Pattern Matching." Russell Nguyen | Sciencx [Online]. Available: https://www.scien.cx/2024/10/06/pattern-matching/. [Accessed: ]
rf:citation » Pattern Matching | Russell Nguyen | Sciencx | https://www.scien.cx/2024/10/06/pattern-matching/ |
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.