views:

112

answers:

3

Hi!

I have a form which encapsulates all the functionality, but works with a concrete Type T1. Now I want to create the same form with the difference, that it will use another Type T2.

T1 and T2 don't inherit from anything, so I can't use inheritance.

How could I do that without copying the whole code again and again?

I was thinking about creating a generic Form, but I don't think that's a correct solution.

Any ideas?

A: 

What do you do with T1 and T2 in the form? If you want to expose/accept values in a strongly typed way, generics sounds like exactly the right approach - although it can be tricky with the WinForms designer, IIRC.

To put it another way: if you weren't using WinForms, would you reach for generics?

Jon Skeet
Yes if I weren't using WinForms I'd use generics, because the Code does the same for all Types..
PaN1C_Showt1Me
In that case I'd look at using generics in this case too. The only downside is the designer support... you may need to create a subclass of the form with a specific type argument in order to get the designer to work.
Jon Skeet
+1  A: 

Write T2, copy all of the code and make sure to encapsulate all the differences in separate methods. Then create a new base class and move the common code from both. A code-sharing design becomes much more obvious (including whether you should use generics) after you have two classes which need it, rather than trying to plan ahead.

Rex M
The problem is that all of those methods are common. Which means that the descendent classes wouldn't have anything inside. That's why I've got a feeling that it tends to Generics..
PaN1C_Showt1Me
A: 

I use a generic element to encapsulate my object, this has a text value and a tag value, it allows for things like what you're trying to do, one good use is for adding to a combo box. Maybe you could incorporate something like this into your form?

public class GenericElement<T> {
    public GenericElement(string text) {
        this.Text = text;
    }
    public GenericElement(string text, T tag) : this(text) {
        this.Tag = tag;
    }
    public T Tag {
        get; set;
    }
    public string Text {
        get; set;
    }
    public override string ToString() {
        return Text;
    }
}

// Combo-Box example
public class MyForm : Form {
    private void DoLoad(object sender, EventArgs e) {
        comboNum.Items.Add(new GenericElement<int>("One", 1);
        comboNum.Items.Add(new GenericElement<int>("Two", 2);
        comboNum.Items.Add(new GenericElement<int>("Three", 3);
    }
    public int SelectedNumber {
        get {
            GenericElement<int> el =
                comboNum.SelectedItem as GenericElement<int>;
            return el == null ? 0 : el.Tag;
        }
    }
}
Brett Ryan