Why I can't use a class that inherits a Shapes
class?
I need to extend the Rectangle
class with some methods, but i want to use this class in the same way I use a Shape
, how can I do?
Why I can't use a class that inherits a Shapes
class?
I need to extend the Rectangle
class with some methods, but i want to use this class in the same way I use a Shape
, how can I do?
You can write a class which derives from
Shape
. You can't write a class which derives fromRectangle
, because that's sealed.As Jon pointed out, Rectangle is sealed.
Depending on what you're trying to do, a couple options are:
You can extend Shape with your own class that contains Rectangle, and augment the functionality through composition. These objects wouldn't be considered Rectangles from an "is" check.
You can write extension methods for Rectangle, and then you can use them on any Rectangle. Then the objects would still be considered Rectangles.
e.g.