Pattern Matching

russellntanh

Russell Nguyen

Posted on October 6, 2024

Pattern Matching

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;
    }
}
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
russellntanh
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.

Related

Demystifying Algorithms: Doubly Linked Lists
datastructures Demystifying Algorithms: Doubly Linked Lists

November 29, 2024

Demystifying Algorithms: Circular Linked Lists
datastructures Demystifying Algorithms: Circular Linked Lists

November 29, 2024

Demystifying Algorithms: Singly Linked Lists
datastructures Demystifying Algorithms: Singly Linked Lists

November 29, 2024

i18n e ASP.NET Core Web API
csharp i18n e ASP.NET Core Web API

November 28, 2024