Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to workaround impossible inheritance from sealed class?

Today im working in WPF.

I tried to inherit from System.Windows.Shapes.Line class, like this:

class MyLine : System.Windows.Shapes.Line
{
    public Ln()
    {
        this.Stroke = Brushes.Black;
    }
}

I just realized, that Line class is sealed.

My goal is to create a class, that will work like Line class (to put it on Canvas), but I don't want to mess my code with adding brush to it everytime, lets say always want black brush/stroke with 2px width.

I feel im trying to do it wrong.

How should I do that?

like image 858
Kamil Avatar asked Mar 24 '23 20:03

Kamil


2 Answers

You could create a factory class:

public class LineFactory
{
    public Line Create(<parameters here>)
    {
        //create and return a Line object
    }
}

The factory could also be static, but that could hinder testability.

Note that this solution doesn't let you extend the Line class as inheritance would. To do that you would need to return a MyLine class which would embed a Line object along with the additional properties you'd want MyLine to have.

public class MyLine
{
    private Line _theBoringOriginal; // composition: "has-a" (vs inheritance "is-a")
    public MyLine(Line line)
    {
        _theBoringOriginal = line;
    }

    public foo SomeProperty { get; set; }
}

If it's just methods you want to extend the Line class with, you don't need a new class, you could just write extension methods in a static class:

public static foo DoSomethingCool(this Line line, <parameters here>)
{
    // whatever
}
like image 170
Mathieu Guindon Avatar answered Apr 02 '23 16:04

Mathieu Guindon


Why not simply create an extension class to do what you want? Extension classes were create specifically to allow you to extend sealed classes with new methods, without having to actually inherit things.

public static class LineExtensions {
    // returns the Line so you can use it fluently
    public static Line MakeLineBlack(this Line line) {
        line.Stroke = Brushes.Black;
        return line;
    }
}

Then you can just do this:

var line = new Line().MakeLineBlack();
like image 34
Erik Funkenbusch Avatar answered Apr 02 '23 16:04

Erik Funkenbusch