Question3r
Question3r

Reputation: 3812

extend sealed class with properties

I want to extend the Rectangle class. Currently this class has the properties left, right, ... and I want to add the properties topLeft, topRight, ...

I know I could create some extension methods like

public static Point TopLeft(this Rectangle rect)
{
    return new Point(rect.Left, rect.Top);
}

but I would like to add this as a property. I thought about inheriting from Rectangle and adding the missing information

internal class Rect : Rectangle
{
    public Point TopLeft
    {
        get
        {
            return new Point(X, Y);
        }
    }

    public Point TopRight
    {
        get
        {
            return new Point(X + Width, Y);
        }
    }
}

but Rectangle is a sealed class.

cannot derive from sealed type 'Rectangle'

So it is not possible to extend this class?

Upvotes: 1

Views: 2447

Answers (1)

Selman Genç
Selman Genç

Reputation: 101701

You can use the adapter pattern:

internal class RectAdapter
{  
    private Rect _rect;

    public RectAdapter(Rectangle rect)
    {
        _rect = rect;
    }

    public Point TopLeft
    {
        get
        {
            return new Point(_rect.X, _rect.Y);
        }
    }

    public Point TopRight
    {
        get
        {
            return new Point(_rect.X + _rect.Width, _rect.Y);
        }
    }
}

You can't inherit from the Rectangle but you can take it as a constructor parameter. And if you don't want to override other behaviour just delegate them to Rectangle by using _rect, for example:

public void Intersect(Rectangle rect) => _rect.Intersect(rect);

Upvotes: 6

Related Questions