Pattern Matching
Russell Nguyen
Posted on October 6, 2024
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;
}
}
💖 💪 🙅 🚩
Russell Nguyen
Posted on October 6, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.